bjskishore123
bjskishore123

Reputation: 6352

Compilation error in usage of templates

template <class T>
class Test
{
public:
 template<class T>
 void f();  //If i define function here itself, error is not reported.
};

template <class T>
void Test<T>::f() 
{
}              //Error here.

int main()
{
 Test<float> ob;
 ob.f<int>();
}

It produces below error.

error C2244: 'Test<T>::f' : unable to match function definition to an
existing declaration

definition 'void Test::f(void)'
existing declarations 'void Test::f(void)'

Error says declaration and definitions have the same prototype but not matching. Why is this an error ? and how to solve it ?

If i define function within the class, it doesn't report error. But i want to define outside the class.

Upvotes: 1

Views: 93

Answers (2)

Prasoon Saurav
Prasoon Saurav

Reputation: 92884

....
public:
  template<class T> // this shadows the previous declaration of typename T
   void f();  
};

Change the parameter name. Here is the working code.

Upvotes: 1

Chubsdad
Chubsdad

Reputation: 25537

Change as

template <class T> 
class Test 
{ 
public: 
 template<class U> 
 void f(); 
}; 

template <class T> 
template<class U>
void Test<T>::f()  
{ 
} 

Upvotes: 2

Related Questions