I have a collection of class objects I want to iterate and I want them to expose a virtual function.
std::vector<Base*> sampleVector;
//...
for (auto t : sampleVector) t->Function();
The most obvious way of dealing with this would be with basic polymorphism
class Base
{
public:
virtual void Function() {} //(or = 0 if I want it to be pure virtual)
}
class Derived : public Base
{
public:
void Function() override { std::cout << "Derived" << std::endl; }
}
On the other hand, a Hybrid CRTP way might be like this
class Base
{
public:
virtual void Function() {} //(or = 0 if I want it to be pure virtual)
}
template <typename T>
class CRTPBase : public Base
{
public:
void Function() override { T::Implementation(); }
}
class Derived : public CRTPBase<Derived>
{
public:
void Implementation() { std::cout << "Derived" << std::endl; }
}
I was thinking that the first one might be better since the resulting API might be more intuitive (user-defined classes would only have to inherit from Base). However the CRTP way doesn't look much less intuitive, and performance might benefit if many Derived classes are defined (simpler virtual method table). What is your opinion on this? Am I overthinking it?