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

Yul*_*a V 3 c++ methods hyperlink specialization

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

在*.h文件中:

class InterfaceFunctionField2 {
public:
    template<class outputType> outputType to() { return outputType(); }
};
Run Code Online (Sandbox Code Playgroud)

在*.cpp文件中

template<> double InterfaceFunctionField2::to<double>()
{    return 3.;  }
Run Code Online (Sandbox Code Playgroud)

该类位于静态库中.

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

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

我已经在互联网上查了一下(例如这里),这种类型的代码似乎没问题,但链接器不同意.你能帮忙吗?谢谢.

Luc*_*ore 5

您还需要在标头中声明特化.

//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.;  }
Run Code Online (Sandbox Code Playgroud)

链接中的代码有效,因为该转换单元可以看到特化.