【问题标题】:Trivial specialization of a method does not work (c++)方法的琐碎专业化不起作用(c ++)
【发布时间】:2025-12-18 04:15:02
【问题描述】:

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

在 *.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),这种类型的代码似乎没问题,但链接器不同意。你能帮忙吗?谢谢。

【问题讨论】:

    标签: c++ methods hyperlink specialization


    【解决方案1】:

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

    //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.;  }
    

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

    【讨论】:

    • 问题发布后不到一分钟的时间就给出了正确答案!非常令人印象深刻,非常感谢。