Can I use CRTP with multiple derived classes and use them polymorphically?

I have a class hierarchy like this:

template <class Type>
class CrtpBase
{
protected:
    Type& real_this()
    {
        return static_cast<Type&>(*this);
    }
};

template <class ChildType>
class Base : CrtpBase<ChildType>
{
public:
    void foo()
    {
        this->real_this().boo();
    }
};

class Derived1 : public Base<Derived1>
{
public:
    void boo { ... }
};

class Derived2 : public Base<Derived2>
{
public:
    void boo { ... }
};

The thing is, I want to use my classes this way:

std::vector<Base*> base_vec;
base_vec.push_bach(new Derived1());
base_vec.push_bach(new Derived2());
.........
base_vec[0]->foo();

But this is impossible, because the base class for all derived classes is different (in fact, Base is not a type at all, it is a template). So, is there a way to use crtp with multiple derived classes along with polymorphism?

+4
source share
1 answer

Indeed, you need to add the appropriate base class without a template:

class AbstractBase
{
public:
  virtual ~AbstractBase() {}

  virtual void foo() = 0;
};


template <class ChildType>
class Base : CrtpBase<ChildType>, public AbstactBase
{
  void foo() override { this->real_this().boo(); }
};

Then declare your vector as std::vector<AbstractBase*>.

( , , CRTP), - ++.

, . , foo , boo - ( , ), foo, , foo, , CRTP-.

, boo -like foo, boo virtual, foo , CRTP. : (foo) (boo).


, std::vector; - .

+3

All Articles