Collection abgeleiteter Klassen



  • Hallo,

    ich rätsle jetzt schon ein par Stunden an nem Stück Code das ich unter http://www.devx.com/tips/Tip/15125 gefunden hab rum.

    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>
    {
    protected:
      Modifier() {vec.push_back(this);}
    private:
      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);

    Wenn ich den Sinn richtig verstehe sollten die abgeleiteten Klassen über den Vector zur Verfügung stehen, allerdings ist die größe immer 1.

    ModifierImpl1 a;
    a.vec.size() //=1 (sichtbarkeit wurde auf public geändert)
    

    Kann mir jemand sagen ob der Code völliger Quatsch ist, ich das ganze nicht richtig verwende oder ich das ganze falsch verstanden hab.
    Falls es kein Quatsch ist wäre ich für eine Erklärung des Codes dankbar.

    Danke im Vorraus....


Anmelden zum Antworten