Call Custom Constructor On Template Typename

276 Views Asked by At

Let's say I have the following code:

Class A
{
public:
    A(B* b)
      : m_B(*b)
    {}

    //Default constructor won't work as it needs to initialize "m_B"
    
private:
    B& m_B;
};

And then I have a class B:

class B
{
public:
    //check that typename is a derivative of A
    template<typename T>
    AddInstance()
    {
        T* instance = new T(this);
        m_Instances.emplace_back(instance);
    }

private:
    std::vector<A*> m_Instances;
};

In this case, I have to construct class A in AddInstance with a constructor which can initialize m_B. Yet when I do this (and I make sure typename derives from A using the following concept: template<typename T> concept Derivative = std::is_base_of<A, T>::value;) I'm unable to initialize the typename variable with anything but the default constructor. If I know for sure that typename inherits from A, is there a way to initialize it through an overloaded constructor?

Note: In my project class A would be an abstract class, and so the typename would be a specialized derivative of A which I would emplace into the vector

Edit So I figured out my issue. I assumed that an inheriting class would be able to call a constructor from its base class. Rather the deriving class needs to create its own constructor that initializes its base class. The whole idea I'm going for with my project is that one should do as little as possible to create a new deriving class, as so I'm trying to do something like this:

AddInstance<Specialization>();

//In AddInstance:
{
    A* instance = new A(this);
    m_Instances.emplace_back(static_cast<Specialization*>(instance));
}

So hypothetically I should be able to construct a new class with A's constructor and then cast it into the desired specialization. Although when I actually do this I just execute A's methods rather than the Specialization's overrides

0

There are 0 best solutions below