Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class factory mixin

Tags:

c++

I would like to create in a mixin class that would impart a class factory method for the final class of a concrete type through several layers of inheritance. More specifically, I would like to have the factory method produce a new instance of the actual object it is called as a member of.

So, class "factory" is inherited by class A, class A is inherited by class B, I would like to find a way to do B::create() and create an instance of B. As far as I can tell this precludes the use of a template taking the type in the class A since then B::create() would produce an instance of A.

like image 358
ddeflyer Avatar asked Jan 27 '26 22:01

ddeflyer


1 Answers

Maybe CRTP would do? http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

template <typename T>
struct Mixin
{
    T * create() const { return new T; }
};

class Target : public Mixin<Target>
{
    ...
};
like image 196
vines Avatar answered Jan 30 '26 12:01

vines



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!