Make a Collection of All Inherited Classes

Make a Collection of All Inherited Classes

Say you want to have several classes-modifiers, and you want to execute a certain virtual function for each of them. The ideal solution is to create an abstract class with a purely virtual function, inherit your implementation classes from this base class and make a collection of all the implementation classes. The problem is that, the user needs to remember to create exactly one copy of each implementation class and correctly “register” it. The following example helps to solve this problem by automatically creating exactly one instance of each implementation of the class modifier:

 #include template  class AutoMake{  virtual void trick() {t;} // virtual function uses _static variable  static T t;};template  T AutoMake::t;template   class Modifier : AutoMake{protected:  Modifier() {vec.push_back(this);}private:  std::vector vec;};class ModifierImpl1 : public Modifier {};class ModifierImpl2 : public Modifier {};That's all: already in main(...) function you will have _2 pointers inModifier::vec (with ModifierImpl1* and ModifierImpl2* types);


Share the Post: