Consider the following construction:
//! Templated singleton. /*! Template wrapper enforcing the singleton behavior. */ template <class T> class TSingleton { private: //! Singleton instance pointer. static T* instance; //! private constructor. TSingleton() { } //! private empty copy constructor. TSingleton(const TSingleton<T>& sourceObject) {} public: //! Static singleton instance getter. static T* GetInstance() { if (instance == 0) instance = new T(); return instance; } }; template <class T> T* TSingleton<T>::instance = 0;
This template class and the definition of the static instance are written to the same header file. For a class other than a template, this results in a connection time error due to the fact that several characters are specified for the static instance member. It seems intuitive that this also happens with templates, so you need to separate the definition and put it in a .cpp file. But templates are usually declared and defined in header files. What allows this syntax to be valid and functional for template classes?
There is a wikipedia link here, but it does not provide a clear explanation of what happens in the case of template classes.
c ++ templates static-members
teodron
source share