title: Singleton C++ template class
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file">Why can templates only be implemented in the header file?</a>  </p>
  </blockquote>
  
  
  
  <p>I realise that there are already few topics like this on SO but I did not find any that would answer my problem. </p>
  
  <p>I have already written my template singleton class using this tutorial <a href="http://www.codeproject.com/Articles/4750/Singleton-Pattern-A-review-and-analysis-of-existin" rel="nofollow noreferrer">http://www.codeproject.com/Articles/4750/Singleton-Pattern-A-review-and-analysis-of-existin</a></p>
  
  <p>but unfortunately I keep on getting errors : </p>
  
  <blockquote>
    <p>/home/USER/testcode/cpp_workshop/main.cpp:-1: error: undefined
    reference to `Singleton::Instance()' :-1: error: collect2: ld</p>
  </blockquote>
  
  <p>my singleton.h</p>
  
  <pre><code>#ifndef SINGLETON_H
  #define SINGLETON_H
  
  template &lt;typename T&gt;
  class Singleton
  {
  public:
      static T&amp; Instance();
  
  protected:
      virtual ~Singleton();
      inline explicit Singleton();
  
  private:
      static T* _instance;
      static T* CreateInstance();
  };
  
  template&lt;typename T&gt;
  T* Singleton&lt;T&gt;::_instance = 0;
  
  #endif // SINGLETON_H
  </code></pre>
  
  <p>singleton.cpp</p>
  
  <pre><code>#include "singleton.h"
  #include &lt;cstdlib&gt;
  
  template &lt;typename T&gt;
  Singleton&lt;T&gt;::Singleton()
  {
      assert(Singleton::_instance == 0);
      Singleton::_instance = static_cast&lt;T*&gt;(this);
  }
  
  template&lt;typename T&gt;
   T&amp; Singleton&lt;T&gt;::Instance()
  {
      if (Singleton::_instance == 0)
      {
          Singleton::_instance = CreateInstance();
      }
      return *(Singleton::_instance);
  }
  
  template&lt;typename T&gt;
  inline T* Singleton&lt;T&gt;::CreateInstance()
  {
      return new T();
  }
  
  template&lt;typename T&gt;
  Singleton&lt;T&gt;::~Singleton()
  {
      if(Singleton::_instance != 0)
      {
          delete Singleton::_instance;
      }
      Singleton::_instance = 0;
  }
  </code></pre>
  
  <p>and that's how I call it (with normall - not templated or anything - class <code>Game</code> )
  <code>Singleton&lt;Game&gt;::Instance().run();</code></p>