I have just read an article about the Curiously Recurring Template Pattern. And you can use it simulate virtual functions with templates.
For example:
template<class T>
struct A
{
void func() { static_cast<T*>(this)->func(); }
};
struct B : public A<B>
{
void func() { cout << "B" << endl; }
};`
However, if we have many subclasses from A and want to put them all in vector, for example, vector<A*> this is not possible when you use templates, and you have to use normal polymorphism with virtual functions in the base class.
What would be a design suggestion to solve this? Because I want to use templates, but also be able to use all subclasses together in a container.
You could do this:
and then create a vector of pointers to
NonTemplateBase(i.e.std::vector<NonTemplateBase *>).However, I’m guessing you want to be able to call
func()or other member functions on the objects in your vector — and you want those calls to polymorphically call the correct member function in the derived class.This isn’t going to work because the Curiously Recurring Template Pattern only allows you to do static (i.e. compile-time) polymorphism. If you want runtime polymorphism, you have to use virtual functions.