Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Feb 20, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <vector>
template <class T> class AutoMake
  virtual void trick() {t;} // virtual function uses _
static variable
  static T t;
template <class T> T AutoMake<T>::t;

template <class T>  class Modifier : AutoMake<T>
  Modifier() {vec.push_back(this);}
  std::vector<Modifier*> vec;

class ModifierImpl1 : public Modifier<ModifierImpl1> {};
class ModifierImpl2 : public Modifier<ModifierImpl2> {};

That's all: already in main(...) function you will have _
2 pointers in
Modifier::vec (with ModifierImpl1* and ModifierImpl2* types);
Mike Melnikov
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date