2013-01-14 65 views
10

我看到相關的模板錯誤(編譯器的Visual Studio 2012),我不理解之外。下面的代碼,歸結爲要領:定義明確的專業類的成員函數的類定義

// Templated class - generic 
template <typename T> 
class Test 
{ 
    public: 
     void WorksFine() {} // Comiples and works as expected at runtime 
     void Problem();  
}; 

// Templated class - expicit specialization for T = int. 
template <> 
class Test<int> 
{ 
     public: 
      void WorksFine() {} // Comiples and works as expected at runtime 
      void Problem(); 
}; 

// The definition below compiles and works fine at runtime. 
template<typename T> void Test<T>::Problem() {} 


// The definition below gives error C2910. 
template<> void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");} 

對於WorksFine方法,函數的定義是的明確專門的類定義,然後一切都很好。但對於問題的方法,當我定義明確專門的類定義之外的方法,我得到錯誤C2910

這是爲什麼?錯誤C2910表示問題是Test :: Problem()已經定義。但它不是定義在類內部......有沒有函數定義只是一個聲明。

根據您選擇放置函數定義的位置,可以做某件事情似乎很蹩腳,但我總是更傾向於風格/語法決策,而不是功能/語義決策。我錯過了什麼嗎?

回答

8

你不需要template<>。只要寫:

void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");} 

template<>語法上的一個成員的專業化要求,其中明確實例化一個成員自身;定義已存在專業化的成員時省略。

template<typename T> struct X { static int i; }; 
template<> int X<int>::i = 0; // member instantiation, uses template<> 

template<typename T> struct Y { static int i; }; 
template<> struct Y<int> { static int i; } // template specialization 
int Y<int>::i = 0; // no template<> 
+0

謝謝,那確實有效! –

0

你不需要template了在明確的功能定義:void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");}

在這種情況下,G ++提供了一個稍微好一點的錯誤消息error: template-id 'Problem<>' for 'void Test<int>::Problem()' does not match any template declaration

0

試試這個:

// The definition below gives error C2910. 
void Test<int>::Problem() 
{ 
    printf("In Test::Problem(int instantiation)\n"); 
} 

int main() 
{ 
    Test<int> hey; 

    hey.Problem(); 
    return 0; 
}; 
+0

謝謝,就是這樣! –

+0

@DavidStone :)沒問題! – tmaric

相關問題