Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive Template idiom how to avoid that the base class is friend of the child classes
    primarykey
    data
    text
    <p>I use the <a href="https://stackoverflow.com/questions/10332725/how-to-automatically-register-a-class-on-creation">recursive template idiom</a> to automatically register all children of a base class in a factory. However in my design the child class must have as a friend class the base class. As the Constructor of my Base class should be private to avoid instantiation of this class other than via the factory.</p> <p>The overal aim would be that the registration of the factory is done in the BaseSolver and the ChildClasses cannot be instantiated other than via the factory.</p> <p>Here is the code of my base class which automatically registers all children in the SolverFactory.</p> <pre><code>template&lt;class T&gt; struct BaseSolver: AbstractSolver { protected: BaseSolver() { reg=reg;//force specialization } virtual ~BaseSolver(){} /** * create Static constructor. */ static AbstractSolver* create() { return new T; } static bool reg; /** * init Registers the class in the Solver Factory */ static bool init() { SolverFactory::instance().registerType(T::name, BaseSolver::create); return true; } }; template&lt;class T&gt; bool BaseSolver&lt;T&gt;::reg = BaseSolver&lt;T&gt;::init(); </code></pre> <p>And here the header file of my child class:</p> <pre><code>class SolverD2Q5 : public BaseSolver&lt;SolverD2Q5&gt;{ private: //how can I avoid this? friend class BaseSolver; SolverD2Q5(); static const std::string name; } </code></pre> <p>This works fine. However I really do not like to have to add the BaseSolver as a friend class, however I <strong><em>do not</em></strong> want the constructor and the static member name to be public. </p> <p>Is there a more elegant solution or a better layout to avoid this?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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