c++ - 方法的简单特化不起作用 (c++)

标签 c++ methods hyperlink specialization

下面的代码(这是我需要的简化版)没有链接

在*.h文件中:

class InterfaceFunctionField2 {
public:
    template<class outputType> outputType to() { return outputType(); }
};

在*.cpp文件中

template<> double InterfaceFunctionField2::to<double>()
{    return 3.;  }

此类位于静态库中。

我收到“错误 LNK2005:”public: double __thiscall InterfaceFunctionField2::to(void)const “(??$to@N@InterfaceFunctionField2@@QBENXZ) 已经在...中定义”和“第二个定义被忽略"警告 LNK4006

我只定义了一次 InterfaceFunctionField2::to() 特化并且我没有#include *.cpp 文件....

我在互联网上查找 ( e.g. here ),这种类型的代码似乎没问题,但链接器不同意。你能帮忙吗?谢谢。

最佳答案

您还需要在 header 中声明特化。

//header.h
class InterfaceFunctionField2 {
public:
    template<class outputType> outputType to() { return outputType(); }
};

template<> double InterfaceFunctionField2::to<double>();

//implementation.cc
template<> double InterfaceFunctionField2::to<double>()
{    return 3.;  }

您链接中的代码有效,因为该翻译单元可以看到特化。

关于c++ - 方法的简单特化不起作用 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10800751/

相关文章:

wordpress - 指向另一个页面上的 anchor 标记的 anchor 链接不起作用

c++ - 合并两个数组后得到不正确的数组大小

c++ - 作为成员变量的 lambda 函数崩溃

c++ - 无法将类成员函数传递给另一个函数 (std::thread::thread)

c++ - CMake:无法运行 MSBuild 命令:MSBuild.exe

java - 在每个方法之前调用方法

java - 使用 if 语句创建一个 for 循环方法返回正确的 "return"没有数组?

python - AttributeError : 'person' object has no attribute 'name'

javascript - Ajax 和防止双重 "submit"

php - 如何将 UNION ALL 查询的结果显示为链接?