【问题标题】:Defining a method with class-level and method-level template parameters [duplicate]使用类级和方法级模板参数定义方法[重复]
【发布时间】:2020-01-20 21:26:18
【问题描述】:

我已经声明了一个这样的类:

snapshot.h

template<typename F>
class Snapshot
{
public:
    template<typename T> void write(T field);
};

#include "snapshot.templates.cpp"

snapshot.templates.cpp

template<typename F, typename T>
void Snapshot<F>::write(T field)
{
    printf("hello world\n");
}

但是编译器给出了错误declaration is incompatible with function template "void Snapshot&lt;F&gt;::write(T)"

write()的定义中指定FT这两个模板参数的正确语法是什么?

【问题讨论】:

  • 如果您打算将模板的声明和实现分成两个文件,其中的实现包含在头文件中,那么我建议不要对实现文件使用.cpp 扩展名。 .cpp 通常表示应该将编译器作为翻译单元的源文件,并且构建系统/IDE 可能会自动以这种方式处理它,从而导致错误或 ODR 违规。模板实现文件的常见扩展名有.tpp.tccothers

标签: c++ templates


【解决方案1】:

由于您有一个模板函数,它是模板类的成员,您需要像这样定义它:

template<typename F>
template<typename T>
void Snapshot<F>::write(T field)
{
    printf("hello world\n");
}

看看live

更新

请注意,您不能将模板类的实现拆分为头文件和源文件,因为编译器需要访问方法的实现才能使用传递的参数实例化它们。如果实现不在标头中,则编译器无法访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多