mora
mora

Reputation: 151

template specialization with template parameter

I have started learning c++ recently. And I sometimes confused with template specialization. Could someone tell me the reason why the following template specialization at No(3) is illegal?

template<typename T>  // No (1)
class ClassA {
public:
    ClassA();
    virtual ~ClassA();

    void func(void);
};

template<>  // No (2)
void ClassA<int>::func(void) {}   // Ok legal specialization

template<typename T>  // No (3)
void ClassA<int>::func(void) {}   // error by compiler

It seems Template specialization at No (3) has no implicit template parameter because typename T is int. But compiler give the following error,

error: prototype for ‘void ClassA<int>::func()’ does not match any in class ‘ClassA<int>’ void ClassA<int>::func(void) {
                           ^

error: candidate is: void ClassA<T>::func() [with T = int] void func(void);
                          ^

I am afraid I am asking a stupid question but I really want to know the reason of error. And I wonder typename Ts at No 1 and No3 are same or not. Please tell me them. Thank you very much.

Upvotes: 0

Views: 93

Answers (2)

Jarod42
Jarod42

Reputation: 217065

(2) is the way to write specialization.

T in (1) and (3) are not really the same, you may write (for non specialization):

template <typename U>
void ClassA<U>::func(void) {}

whereas it was T in (1)

or partial specialize

template <typename T>
void ClassA<std::vector<T>>::func(void) {}

where here the T1 in (1) would be std::vector<T3>.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206557

Instead of

template<typename T>
void ClassA<int>::func(void) {}

Use

template<typename T>
void ClassA<T>::func(void) {}
        // ^^^ T, not it.

I am not sure whether the use of int was on purpose or it was an oversight.

Upvotes: 0

Related Questions