Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>the best way do to this is using CRTP (curiously recurring template pattern), the derived classes ARegister and BRegister pass themselves as template arguments to the base class RegisterALL. It will look like this:</p> <pre><code>class RegisterAll { public: template&lt;class DerivedType&gt; DerivedType *createType() { RegisterAll *r = (*(m_creators[DerivedType::id]))(); return dynamic_cast&lt;DerivedType *&gt;(r); //static_cast will work too if you didn't make a mistake } protected: static std::map&lt;int,RegisterAll *(*)()&gt; m_creators; }; std::map&lt;int,RegisterAll *(*)()&gt; RegisterAll::m_creators = std::map&lt;int,RegisterAll *(*)()&gt;(); template&lt;class Derived&gt; class CRTPRegisterAll : public RegisterAll { public: static bool register() { RegisterAll::m_creators.push_back(std::make_pair(Derived::id,Derived::create); return true; } private: static bool m_temp; }; template&lt;class Derived&gt; bool CRTPRegisterAll&lt;Derived&gt;::m_temp = CRTPRegisterAll&lt;Derived&gt;::register(); class RegisterA : public CRTPRegisterAll&lt;RegisterA&gt; { private: static RegisterA *create() { //do all initialization stuff here return new RegisterA; } public: static const int id = 0; }; </code></pre> <p>Now the initialization of the static variable <code>m_temp</code> in <code>CRTPRegisterAll</code> pushes a creator function for each derived type onto <code>RegisterAll</code>'s list. It is generally not very good design to have <code>RegisterAll</code> know about all the derived classes (it isn't very extensible). This way the actual creation method can be implemented in each derived class and the creator function will be automatically registered in <code>RegisterAll</code>. One of the main advantages of CRTP is that the derived classes don't need to know how to register themselves to the base class' list, it is done for them. As for error handling that too can be implemented in each derived class' creator functions. There are better ways to handle the id issue but I don't want to get into that here. If you want a simpler method I suggest reading about the Factory design pattern.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload