C++ 具有浮点数的模板专用化
C++ Template specialization with float
我在标题中有这段代码
class MyMathUtils {
template <typename T> static bool IsEqual(const T & val1, const T & val2);
};
template <typename T>
bool MyMathUtils::IsEqual(const T & val1, const T & val2)
{
return (val1 == val2);
};
这在 cpp 中
template <>
bool MyMathUtils::IsEqual<float>(const float & val1, const float & val2)
{
if ((val1 - val2) < -EPSILON) return false;
if ((val1 - val2) > EPSILON) return false;
return true;
}
问题是,编译器给了我这个错误:
MyMath::MyMathUtils::IsEqual(float const &,float const &)" (??$IsEqual@M@MyMathUtils@MyMath@@SA_NABM0@Z) 已在 中定义 MyMathUtils.obj;忽略第二个定义
但是如果我使用相同的,但我放了双精度而不是浮点数,它被正确编译。这里有什么不正确的,我错过了?
您需要在标头中声明专用化。
namespace MyMathUtils {
// generic template (shouldn't be static)
template <typename T> bool IsEqual(const T & val1, const T & val2);
// explicit specialisation
template <> bool IsEqual<float>(const float & val1, const float & val2);
// alternatively, overloading would be simpler
bool IsEqual(float, float);
};
(我冒昧地将其更改为命名空间,而不是类,因为这更有意义。如果你出于某种原因确实希望它是一个类,你必须在外面的命名空间中声明专用化。
否则,在其他翻译单元中使用它将导致它从泛型模板实例化,因为编译器不知道显式专用化的存在。这会导致多个定义。
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 使用提升将数据从 PyObject 复制到浮点数 *
- 使用浮点数和双精度数的非常小数字的数学
- 使用英特尔内联函数将打包的 8 位整数乘以浮点数向量
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 返回浮点数的小数位数
- txt 文件中浮点数的最大和最小值
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 将浮点数转换为无符号字符数组并打印出来
- 如何将时间字符串 (M:SS) 转换为浮点数
- 如何将浮点数(*)[6]转换为浮点**类型?
- C++将浮点数乘以分数
- 如何将浮点数转换为uint8_t?
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 在数学上将浮点数四舍五入到 N 位小数
- Cython通过浮点数的最快方式,用于高频控制回路
- C++ 具有浮点数的模板专用化