将模板类型与常数数值值进行比较
Comparing template type to constant number value
是否有更好的方法来执行以下操作?
我有一个向量类,具有以下功能:
template <typename T>
bool Vector3<T>::IsUnitVector() const
{
return IsAlmostEqual(this->GetLength(), One<T>::Value());
}
t可以是浮动或双重的(我正在使用明确的模板实例化来确保仅支持这些类型),我必须创建一个辅助类,该类别以正确的类型返回1个值:
template <typename T>
struct One
{
static T Value();
};
template <>
struct One<int>
{
static int Value() { return 1; }
};
template <>
struct One<float>
{
static float Value() { return 1.0f; }
};
template <>
struct One<double>
{
static double Value() { return 1.0; }
};
这还不错,直到我意识到我需要创建一个Zero
类以进行其他比较。所以我的问题是,有一种更好的方法来实现这一目标吗?
return IsAlmostEqual(this->GetLength(), static_cast<T>(1));
小,非负整数值都应完全由每种数字类型代表,因此仅static_cast
'到所需的类型就足够了。
另外,假设IsAlmostEqual
是一个静态成员函数,它具有T
类型的两个参数(例如IsAlmostEqual(T lhs, T rhs)
),只需让编译器在函数调用中自动执行转换:
return IsAlmostEqual(this->GetLength(), 1);
为什么不让编译器进行转换工作
template<typename T, int val>
bool Vector3<T>::_isConstant()const{
return IsAlmostEqual(this->GetLength(), val);
}
template <typename T>
bool Vector3<T>::IsUnitVector() const{
return _isConstant<T,1>();
}
template<typename T>
bool Vector3<T>::IsZeroVector()const{
return _isConstant<T,0>();
}
不确定语法是否正确,但这就是一般的想法。
template <typename T>
struct Value
{
static T Zero();
static T One();
};
template <>
struct Value<int>
{
static int Zero() { return 0; }
static int One() { return 1; }
};
// .. and so on
相关文章:
- 比较字符数组
- 如何在C++中比较两个char数组
- 比较if语句中的数组值和int值
- 数数并选择 sqlite 中的前三名
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 比较 c++ 中的字符数组
- 如何将字符串字符与结构数组进行比较?
- dev如何在C++中比较二进制数
- 将constexpr字节数组与缓冲区的一部分(指向数据的指针)进行比较
- 在C++中返回基元类型数组(Java比较)
- 谷歌测试比较指针数组的内容
- 数数并说在C++中使用递归
- 从数组比较2个字符串时,程序崩溃
- C++ 更快的字符数组比较
- 如何将小数数组转换为二进制数数组
- 将变量与大十六进制数进行比较
- c++数组比较和移动?为什么苹果不动?
- c++中浮点数/双精度数的比较
- 快速数组比较和替换最接近值的元素的算法.(跟踪点)
- 加速c++中双精度数的比较