将模板类型与常数数值值进行比较

Comparing template type to constant number value

本文关键字:数数 比较 类型 常数数      更新时间:2023-10-16

是否有更好的方法来执行以下操作?

我有一个向量类,具有以下功能:

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