C++ Mixins - Is this the correct way of implementing?

163 Views Asked by At

Hi all I have created a mixin class (super contrived) for printing out elements T (of some type T) which have a method called name().

I am wondering if this is considered the correct way to implement in C++?

Any comments are welcome.

template<class T>
struct name_method_printer_to_console_mixin{
    void print() const{
        auto& that = static_cast<T const&>(*this);
        cout << "Mixin printing name which is: " << that.name() << endl;
    }
};

class customer : public name_method_printer_to_console_mixin<customer>{
public:
    customer(){}
    customer(string const &name) : name_(name){}
    string const & name() const{
        return name_;
    }
private:
    string name_;
};

Blair

1

There are 1 best solutions below

0
On

Looks valid. Not sure it's useful, but that's par for the super-contrived course.

I'd suggest casting the pointer and using that->name() instead of references. They do the same thing, but the pointer would be easier to understand