Is this the correct way to initialize static data members of template classes?
template <typename T>
class Temp
{
public:
static unsigned int x;
};
template <typename T>
unsigned int Temp<T>::x = 0;
We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.
The initializer for a static data member is in the scope of the class declaring the member. A static data member can be of any type except for void or void qualified with const or volatile . You cannot declare a static data member as mutable . You can only have one definition of a static member in a program.
Which is the correct syntax for declaring static data member? Explanation: The syntax must firstly be mentioned with the keyword static. Then the data type of the member followed by the member name should be given.
Static data members and templates (C++ only) The static declaration can be of template argument type or of any defined type. The statement template T K::x defines the static member of class K , while the statement in the main() function assigns a value to the data member for K <int> .
Yes. Yes, it is.
[C++11: 14.5.1.3/1]
A definition for a static data member may be provided in a namespace scope enclosing the definition of the static member’s class template. [ Example:template<class T> class X { static T s; }; template<class T> T X<T>::s = 0;
—end example ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With