How to automatically register a class on creation

前端 未结 6 1620
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 03:50

I was wondering whether a design pattern or idiom exists to automatically register a class type. Or simpler, can I force a method to get called on a class by simply extendin

6条回答
  •  鱼传尺愫
    2020-11-29 04:11

    You can indeed do this using the curiously recursive template idiom. It requires nothing from whoever is extending the class that can't be enforced by the compiler:

    template
    struct Animal
    {
       Animal()
       { 
          reg;  //force specialization
       }
       virtual std::string name() = 0;
       static bool reg;
       static bool init() 
       { 
          T t; 
          AnimalManager::registerAnimal(t.name());
          return true;
       }
    };
    
    template
    bool Animal::reg = Animal::init();
    
    struct Tiger : Animal
    {
       virtual std::string name() { return "Tiger"; }
    };
    

    In this code, you can only extend Animal if you specialize it. The constructor forces the static member reg to be initialized, which in turn calls the register method.

    EDIT: As pointed out by @David Hammen in the comments, you won't be able to have a collection of Animal objects. However, this can easily be solved by having a non-template class from which the template inherits and use that as a base class, and only use the template for extending.

提交回复
热议问题