下面的代码(这是我需要的简化版)没有链接
在*.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/