C ++ templates and static members - definition in title

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.

+8
c ++ templates static-members
source share
1 answer

This works because [basic.def.odr]/5 explicitly allowed duplication of templates:

There can be more than one definition of a class type (section 9), an enumeration type (7.2), a built-in function with external communication (7.1.2), a class template (section 14), a non-static function template (14.5.6), a static data element of a class template (14.5.1.3), a member function of a class template (14.5.1.1) or a specialized specialization of a template for which some template parameters are not specified (14.7, 14.5.5) in the program, provided that each definition appears in a different translation unit and when provided that the definitions satisfy the following requirements ....

The requirements are quite long, so I won’t duplicate them here, but in essence they state that each duplicate definition must be identical (otherwise the program has undefined behavior).

+13
source share

All Articles