专门的内部类模板的功能的外层定义?

And*_*zos 5 c++ templates template-specialization c++11 c++14

请考虑以下不正确的计划:

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
Run Code Online (Sandbox Code Playgroud)

为什么没有f编译的定义?如何f在上面正确定义功能?

Bar*_*rry 8

clang错误在这里非常有用:

no function template matches function template specialization 'f'
// ^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

您使用的语法是函数模板.但f它不是一个功能模板,它只是一个功能.要定义它,我们不需要template关键字:

void S::J<void>::f() {}
Run Code Online (Sandbox Code Playgroud)

此时,S::J<void>只是另一个类,所以这与您的标准没有什么不同:

void Class::method() { }
Run Code Online (Sandbox Code Playgroud)

只有template在定义模板的成员函数时才需要,例如:

template <typename T>
void S::J<T>::g() { }
Run Code Online (Sandbox Code Playgroud)

或成员函数模板:

template <typename T>
void S::J<void>::h<T>() { }
Run Code Online (Sandbox Code Playgroud)