// Example program
#include <iostream>
#include <string>
#include <vector>
template<typename T> class Base {
public:
void Run() { returnstatic_cast<T*>(this)->DoIt(); }
};
class Derived1 : public Base<Derived1> {
public:
void DoIt() { std::cout << "d1" << std::endl; }
};
class Derived2 : public Base<Derived2> {
public:
void DoIt() { std::cout << "d2" << std::endl; }
};
The problem with this pattern is that I can't have a std::vector of Base-classes because Base is a class template, so I can only instanciate classes themselves, right?
1 2 3 4 5 6 7
int main() {
Derived1 Obj1;
Derived2 Obj2;
Obj1.Run(); /* runs the actual DoIt() implementation */
Obj2.Run(); /* runs the actual DoIt() implementation */
};
2.) When I want to store the Objects in a std::vector<Base*> I could make a non-template base class and a derive_helper<T> class.
The function run has to be virtual because Base does not know what type derives from it but I want to be able to call it on a Base-Object...
Now I have basically combined static and dynamic polymorphism.
Do I still get a better performance? (it wouldn't make sense to me)