Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template class - member function specialization

Tags:

c++

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;
like image 365
Irbis Avatar asked Dec 28 '13 17:12

Irbis


People also ask

Can member functions be declared as template?

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.

What is the difference between template class and template function?

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 ++?

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.

What is function template specialization?

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.


1 Answers

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 by template<>. [..]

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 the template<> syntax. [..]

… but that does not apply here.

like image 55
Lightness Races in Orbit Avatar answered Sep 25 '22 15:09

Lightness Races in Orbit