What does `class template Example<int>;` statement mean with C++11?

  • A+
Category:Languages

I've been referred to Explicit Template Instantiation article on cplusplus.com which gives the following example:

template <typename T> class Example { public:     Example( T test )     {         _data = test;     }     void setTest(T test)     {         _data = T;     } private:     T _data; };  class template Example<int>; class template Example<float>; class template Example<double>; 

Apart from what looks like an omission error to me where a type is attempted to be assigned to a member variable -- _data = T instead of what I assume should be _data = test -- what I don't understand is what do the last 3 lines declare or instruct the compiler to do, exactly?

I know what templates are, have built programs with them, and know in general about their instantiation and specialization. I do probably have some holes in the understanding of the latter two, but I typically instruct an explicit template instantiation using e.g. template class Example<int>; form and not the one shown in the snippet.

I've tried to compile the snippet using g++ -std=c++11 -pedantic and it compiles just fine and without warnings (I corrected the _date = T error above first).

This came after I commented on an answer to a related question and I am still unsure whether either of the last 3 lines in the snippet is a template specialization or instantiation.

I have also tried to locate the relevant grammar production rule (one allowing template after class) in the C++11 draft published by ISO but came empty handed.

 


We can see from the following godbolt example this is ill-formed according to clang and MSVC and looking at the draft standard section on Explicit instantiation section [temp.explicit] I don't know why gcc accepts it.

I believe what the article "possibly" meant given the topic was:

template class Example<int>; template class Example<float>; template class Example<double>; 

and that indeed does look well-formed with gcc/clang/MSVC.

cppreference has a good dicssuion of Explicit instantiation and this SO question Explicit instantiation - when is it used? explains more details why this is useful.

Also note, we can see this Meta post: Links being changed to cppreference.com that the site has been known to have incorrect information and in general the community prefers cppreference as a solid C++ reference.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: