4

Possible Duplicate:
「invalid use of incomplete type」 error with partial template specialization成員函數的偏特

爲什麼我能做到這一點:

template <typename T> 
struct A 
{ 
    void foo(int); 
}; 

template <> 
void A<int>::foo(int) 
{ 
} 

但不是這樣的:

template <typename> struct C {}; 

template <typename T> 
struct A 
{ 
    void foo(int); 
}; 

template <typename T> 
void A<C<T> >::foo(int) 
{ 
} 

對於第二種情況,GCC提供了以下錯誤:

test.cpp:10:23: error: invalid use of incomplete type 'struct A<C<T> >' 
test.cpp:4:8: error: declaration of 'struct A<C<T> >' 

編輯

當解釋爲什麼第二個例子是不允許的,也請考慮使成員函數也是一個模板有沒有效果上示例工作,哪些不是。也就是說,這仍然有效:

template <typename T> 
struct A 
{ 
    template <typename U> 
    void foo(U); 
}; 

template <> 
template <typename U> 
void A<int>::foo(U) 
{ 
} 

但這並不:

template <typename> struct C {}; 

template <typename T> 
struct A 
{ 
    template <typename U> 
    void foo(U); 
}; 

template <typename T> 
template <typename U> 
void A<C<T> >::foo(U) 
{ 
} 

這樣的理由不能是函數模板只能是完全專用的,因爲第三個例子是不是一個完整的專業化(模板參數U仍然存在),但它的工作原理。

+0

@Mankarse似乎是一個不同的問題。 –

回答

6

功能模板只能完全專用,而不能部分。

您正在使用類模板的成員函數本身是函數模板的事實,所以此規則仍然適用。


至於你的編輯:下面的東西都可以明確地(即完全)專業,從14.7.3/1:

An explicit specialization of any of the following:

— function template

— class template

member function of a class template

— static data member of a class template

— member class of a class template

— member enumeration of a class template

— member class template of a class or class template

member function template of a class or class template

can be declared by a declaration introduced by template<>;

我強調的是適用於您的情況下,這兩種說法。在沒有任何其他明確規定的情況下,這些實體可以部分專用而不是

+0

我不確定我是否買這個解釋。假設我使用模板參數'U'將成員函數本身作爲模板。那麼我仍然可以定義'A :: foo(U)',但不能'A > :: foo(U)'。然而,第一個很難被認爲是完全專業化的,因爲它有一個模板參數('U')。 – HighCommander4

+0

@ HighCommander4:我說「成員函數」,而不是「成員模板」。如果你改變了這個問題,我改變了答案:-) –

+0

完成,請看我的編輯:) – HighCommander4