title: C++ templates and static members - definition in the header
body: <p>Consider the following construct:</p>
  
  <pre><code>//! Templated singleton.
  /*!
      Template wrapper enforcing the singleton behavior.
  */
  template &lt;class T&gt;
  class TSingleton
  {
  private:    
      //! Singleton instance pointer.
      static T* instance;
      //! private constructor.
      TSingleton() { }
      //! private empty copy constructor.
      TSingleton(const TSingleton&lt;T&gt;&amp; sourceObject) {}
  
  public:
      //! Static singleton instance getter.
      static T* GetInstance()
      {
          if (instance == 0)
              instance = new T();
          return instance;
      }
  
  };
  
  template &lt;class T&gt; T* TSingleton&lt;T&gt;::instance = 0;
  </code></pre>
  
  <p>This template class and the definition of the static instance are written in the same header file. For a non-template class, this <em>causes a link-time error due to multiple symbols being defined for the instance static member</em>. It seems intuitive for this to happen with templates as well, thus one must separate the definition and put it in a .cpp file. But templates are usually declared and defined in header-like files. <strong><em>What is it that allows this syntax to be valid and functional for template classes?</em></strong> </p>
  
  <p>There a <a href="http://en.wikipedia.org/wiki/One_definition_rule">wikipedia</a> link on this, but it does not provide a clear explanation on what happens in case of template classes.</p>