Note that there are some explanatory texts on larger screens.

plurals
  1. POTemplated Singleton Policy using CRTP in C++
    text
    copied!<p>There are many folks out there that claim their singleton implementation to be robust and general because it uses metaprogramming constructs.</p> <p>My goal is to enforce a singleton policy onto a derived class so that I do not have to explicitly (manually) declare the derived class' constructors as private. I think there's a way to naively add the instance static variable and the getter as a policy by making the templated singleton a friend of the class you derive. But that's not at all elegant.</p> <p>I started with this code, that, among other things, is given as being a correct (i.e. complete) design of a singleton, while it is clearly allowing for multiple instances:</p> <pre><code>template &lt;class CWrappedClass&gt; class CSingleton { protected: static CWrappedClass* ms_instance; private: CSingleton(){} CSingleton(const CSingleton&amp; ) {} CSingleton&amp; operator = (const CSingleton&amp;) {} public: static CWrappedClass&amp; GetInstance() { if (ms_instance == NULL) ms_instance = new CWrappedClass; return *ms_instance; } }; template &lt;class CWrappedClass&gt; CWrappedClass* CSingleton&lt;CWrappedClass&gt;::ms_instance = NULL; </code></pre> <p>And a singleton client of this "policy", using CRTP:</p> <pre><code>class CThing : public CSingleton&lt;CThing&gt; { // friend class CSingleton&lt;CThing&gt;; // only if ctor is private! public: void DoNothing() { std::cout&lt;&lt;" Nothing \n"; } CThing() { std::cout&lt;&lt;" single "; } }; </code></pre> <p><strong>NOTE</strong> this is not a correct implementation of a CRTP Singleton policy, it's merely part of the question!</p> <p>The code <em>won't</em> compile as is. The base singleton policy class has its constructor declared private, so it can't support derived instances unless the child is a friend of this class. People usually make the constructors protected, which means there's nothing to keep a user from making derived class non-singletonian.</p> <p><strong>Problem/Question</strong>: Is there any mechanism to enforce a singleton policy without having to make the derived class' constructors private manually?</p>
 

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