以下代码(这是我所需要的简化版本)未链接
在* .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.; }
链接中的代码有效,因为特化对该翻译单元可见。