Here is an example code:
template<class T>
class A
{
public:
A(T t): x(t){}
T getX();
private:
T x;
};
template<class T>
T A<T>::getX()
{
return x;
}
// member function specialization
template<> // works with and without template<>
long A<long>::getX()
{
return 1000L;
}
The above code works with and without template<> before a member function specialization. Why ? What difference does it make in such case ?
Edit1: I use that template this way (VS 2012 compiler):
A<int> a1(1);
cout<<a1.getX()<<endl;
A<long> a2(1);
cout<<a2.getX()<<endl;
The term member template refers to both member function templates and nested class templates. Member function templates are function templates that are members of a class or class template. Member functions can be function templates in several contexts.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
What are the two specializations of I/O template classes in C++? Explanation: The I/O specialization is made with wide character and 8-bit characters.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Not compliantly, it doesn't.
FWIW, GCC 4.8 rejects your code without the template <>
.
Your compiler is either buggy or has an extension to support this; I can confirm that MSVS 2012 accepts the code. I'm told that MSVS 2013 November CTP also eats it up without complaint. To be fair, Visual Studio was always fairly lenient about template specifications.
[C++11: 14.7/3]:
An explicit specialization may be declared for a function template, a class template, a member of a class template or a member template. An explicit specialization declaration is introduced bytemplate<>
. [..]
The only exception to this rule is:
[C++11: 14.7.3/5]:
[..] Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using thetemplate<>
syntax. [..]
… but that does not apply here.
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