Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function syntax in class template specialization

I have a class template, let's call it A, which has a member function abc():

template <typename T>
class A{
public:
    T value;
    void abc();
};

I can implement the member function abc() outside the class declaration, using the following syntax:

template <typename T>
void A<T>::abc()
{
    value++;
}

What I want to do is to create a template specialization for this class, let's say int.

template <>
class A<int>{
public:
    int value;
    void abc();
};

The question is: what is the correct syntax to implement abc() for the specialized class?

I tried using the following syntax:

template <>
void A<int>::abc()
{
   value += 2;
}

However this doesn't compile.

like image 489
Tibi Avatar asked Sep 04 '12 09:09

Tibi


2 Answers

void A<int>::abc()
{
   value += 2;
}

since A<int> is explicit specialisation of A<T>.

http://liveworkspace.org/code/982c66b2cbfdb56305180914266831d1

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

[ Example:

template<class T> struct A {
struct B { };
template<class U> struct C { };
};
template<> struct A<int> {
void f(int);
};
void h() {
A<int> a;
a.f(16);
}
// A<int>::f must be defined somewhere
// template<> not used for a member of an
// explicitly specialized class template
void A<int>::f(int) { /∗ ... ∗/ }

like image 193
ForEveR Avatar answered Nov 02 '22 12:11

ForEveR


Remove the template<>:

void A<int>::abc()
{
   value += 2;
}
like image 42
ecatmur Avatar answered Nov 02 '22 12:11

ecatmur