首页 > 解决方案 > C++ 专用方法模板产生多个定义错误

问题描述

我正在使用 C++ 98。我正在编写一个 JSON 对象包装器。对于所有普通数字,它们可以使用相同的函数,但对于浮点数和双精度数,我需要一个单独的函数。字符串也一样。我使用模板和专业化编写了这个,它编译得很好,但是当我构建我的整个项目时,我得到了大约 10 亿个关于多个定义的错误。我假设我没有正确专业化。我能够在类对象本身中有和没有这些定义的情况下编译这个文件,所以我什至不知道是否需要这些定义。

class Object {
    public:
        template <class T>
        bool Set(std::string key, T value);
        // having these defined or not doesn't seem to matter
        bool Set(std::string key, double value);
        bool Set(std::string key, float value);
        bool Set(std::string key, std::string value);
};


template <class T>
bool Object::Set(std::string key, T value){
}

template <>
bool Object::Set<double>(std::string key, double value){
}


template <>
bool Object::Set<float>(std::string key, float value){
}

template <>
bool Object::Set<std::string>(std::string key, std::string value){
}

如何正确专门化这些模板,以使编译器/链接器不适合?

标签: c++c++98

解决方案


如果您在头文件中的类外部定义模板的成员函数的特化,则需要inline像这样进行特化:

template <> 
inline bool Object::Set<double>(std::string key, double value){
}

template <>
inline bool Object::Set<float>(std::string key, float value){
}

template <>
inline bool Object::Set<std::string>(std::string key, std::string value){
}

推荐阅读