2010-10-31 70 views
1
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>(); 
} 

它會產生以下錯誤。模板使用中的編譯錯誤

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

定義 '無效的Test :: F(無效)'
現有的宣言 '無效的Test :: F(無效)'

錯誤說的聲明和定義具有相同的原型,但不匹配。 這是什麼錯誤?以及如何解決它?

如果我在類中定義函數,它不會報錯。 但我想在課堂外定義。

回答

2

變化

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

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

+1:工作,謝謝。 – bjskishore123 2010-10-31 03:48:59

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

更改參數名稱。 Here是工作代碼。

+0

+1:澄清陰影概念。 – bjskishore123 2010-10-31 03:49:26