2015-02-11 80 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