【问题标题】:Out-of-class definition of function of specialized inner class template?专门的内部类模板的函数的类外定义?
【发布时间】:2015-02-11 13:21:45
【问题描述】:

请考虑以下格式错误的程序:

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

【问题讨论】:

    标签: c++ templates c++11 c++14 template-specialization


    【解决方案1】:

    clang 错误在这里很有帮助:

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

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

    void S::J<void>::f() {}
    

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

    void Class::method() { }
    

    如果您要定义模板的成员函数,则只需要 template,例如:

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

    或成员函数模板:

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

    【讨论】:

    • "如果您要定义模板的成员函数,则只需要 template" 或模板成员函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多