Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the correct way to initialize static data members of template classes?

Tags:

c++

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;
like image 605
NFRCR Avatar asked Apr 07 '14 18:04

NFRCR


People also ask

How do you initialize static members of a class?

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.

Where should you initialize a static data member?

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.

What is the correct syntax of initialization of static member?

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.

How are static members declared within a template class?

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> .


1 Answers

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 ]

like image 129
Lightness Races in Orbit Avatar answered Sep 19 '22 04:09

Lightness Races in Orbit