mercredi 6 juillet 2016

Iterate over different CRTP Derived class methods

In an example below I have a pretty typical CRTP example, two different derived classes that both have a method bar. The base class has a method foo which just forwards to some derived bar method #include <iostream> template<typename Derived> class Base { public: void foo() { static_cast<Derived*>(this)->bar(); } }; class DerivedA : public Base<DerivedA> { public: void bar() { ::std::cout << "An"; } }; class DerivedB : public Base<DerivedB> { public: void bar() { ::std::cout << "Bn"; } }; int main() { DerivedA a; DerivedB b; a.foo(); b.foo(); } It doesn't seem like I can have an array / vector / etc. of the base class because it would have to have a type along the lines of Base<T> where T is different Is there some kind of convention without virtual for being able to iterate over different derived classes assuming they all have the same method (bar in this case)?

Aucun commentaire:

Enregistrer un commentaire