Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>EDIT: Added more explanation to the codes.</p> <p>A solution with templates would be as follows:</p> <p>I have created a template for classes that should have an instance with global access when created. I think this is what you want. (I have named it as Singleton reffering to the design pattern with the name) .h:</p> <pre><code>// C++ header for template Singleton template&lt;typename T&gt; class Singleton : public T { static Singleton&lt;T&gt;* instance; Singleton(); public: static Singleton&lt;T&gt;* getInstance(); }; </code></pre> <p>getInstance() method will be from where you will get that instance. It can be an object instead of a pointer, but I like it better this way because it's more versatile with you want to do something more complex like changing the instance at runtime; also it allows to instantiate the object only when it is used, preventing no need memory alloc. .cpp:</p> <pre><code>// C++ source for template Singleton template&lt;typename T&gt; Singleton&lt;T&gt;* Singleton&lt;T&gt;::instance = NULL; template&lt;typename T&gt; Singleton&lt;T&gt;::Singleton() : T() {} template&lt;typename T&gt; Singleton&lt;T&gt;* Singleton&lt;T&gt;::getInstance() { if (instance == NULL) { instance = new Singleton&lt;T&gt;(); } return instance; } </code></pre> <p>You can implement any class you want normally and use Singleton template to ensure that you will always dealing with the same global instance of some class. You can also use a typedef to caliry type names, if you want. Your class definition:</p> <pre><code>// Definition of class foobar class foobar_impl { public: int a; }; typedef Singleton&lt;foobar_impl&gt; Foobar; </code></pre> <p>Then, you use the template to retreave the instance of foobar_impl:</p> <pre><code>int main(int argc, char** argv) { Foobar *pf = Foobar::getInstance(); return 0; } </code></pre> <p>The problem of this solution, however, is that Singleton template will work only with classes that have an empty constructor. But so does your examples, so I think this is what you want.</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