Is there anything better than a metafactory to work around constructor injection into derived classes in CRTP?

前端 未结 2 547
南笙
南笙 2021-01-02 03:08

In the CRTP, I want to inject the constructor into the derived class, cleanly - without use of macros and without writing it out. It seems it\'s impossible, so I\'ve come up

2条回答
  •  礼貌的吻别
    2021-01-02 03:16

    I think what you're looking for might be just using placement new to instantiate the base class.
    The derived class won't be constructable because unless they will create a matching constructor.
    But, they don't have to be constructable, you could use them anyway. (It could still be destructable).

    template 
    class Base
    {
    protected: Base(int blah) { }
    
    public: static T* CreateInstance(int data) { 
                T* newOjectBlock =  reinterpret_cast(::operator new(sizeof(T))); // allocate enough memory for the derived class
                Base* newBasePlace = (Base*)(newOjectBlock); //point to the part that is reseved for the base class
                newBasePlace=  new ((char*)newBasePlace) Base(data); //call the placement new constrcutor for the base class
                return newOjectBlock;
            }
    };
    
    class Derived : public Base {}
    

    Then let the CRTP base class construct the derived class like this:

    Derived* blah =  Derived::CreateInstance(666);
    

    If anyone ever wants to initialize the derived class, they should either make a matching constructor that calls the base class constructor.
    OR, just make an .init() method that initiates its members, and will be called after the instance is created.

    OR, we can think of something else, this is just an idea of a concept.

提交回复
热议问题