c++ - 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){
}
如何正确专门化这些模板,以使编译器/链接器不适合?
解决方案
如果您在头文件中的类外部定义模板的成员函数的特化,则需要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){
}
推荐阅读
- c# - 请求 URL 太长 HTTP 错误 414。请求 URL 太长
- python - NMap Python for循环未运行
- java - Java中的自动转换问题
- azure - Azure Functions ARM 模板部署删除 Functions
- arrays - Ruby - 将带有嵌套数组的 JSON 文件解析为 ruby 哈希,而不会丢失数据
- c# - 具有对象列表的模拟通用方法
- javascript - 在 Javascript 中将行与列相关联
- python - 使用布尔掩码从现有数组构建新数组
- python - OSError:[Errno 7] 参数列表太长:'php' - Python 3.6
- r - 'file' 必须是字符串或连接