2015-02-11 78 views
5

請考慮以下病態的程序:專門的內部類模板的功能的類外定義?

struct S { 
    template<class T> struct J { }; 
}; 

template<> 
struct S::J<void> { 
    void f(); 
}; 

template<> 
void S::J<void>::f() {} // ERROR 

$ clang++ -std=c++11 test.cpp 
no function template matches function template specialization 'f' 

$ g++ -std=c++11 test.cpp 
template-id ‘f<>’ for ‘void S::J<void>::f()’ does not match any template declaration 

爲什麼不的f定義編譯?如何在上面正確定義函數f

回答

8

鐺錯誤是非常有幫助的位置:

no function template matches function template specialization 'f' 
// ^^^^^^^^^^^^^^^^^ 

您正在使用的語法是一個函數模板。但f不是函數模板,它只是一個函數。要定義它,我們不需要template關鍵字:

​​

在這一點上,S::J<void>只是另一個類,所以這是沒有比你的標準不同:

void Class::method() { } 

你只願意需要template如果你定義模板的成員函數,例如:

template <typename T> 
void S::J<T>::g() { } 

或成員函數模板:

template <typename T> 
void S::J<void>::h<T>() { } 
+0

「*如果您正在定義模板的成員函數*」或模板成員函數,則只需要'template'。 – ildjarn 2015-02-11 13:54:26

+0

@ildjarn更新 – Barry 2015-02-11 14:00:20