根据浮点数选择最小整数类型

Choose smallest integer type based on a float

本文关键字:整数 类型 选择 浮点数      更新时间:2023-10-16

我正在尝试编写一个包含变量的类,该变量的类型将被选择为能够包含值的最小可能。

我的意思是:

class foo {
 "int type here" a;
}

我遇到了自动选择一个足够大的变量类型来容纳指定的数字。由于使用提升库时遇到困难,我继续使用模板建议。

这会将代码转换为:

template<unsigned long long T>
class foo {
 SelectInteger<T>::type a;
}

但是,我的问题源于变量的大小是将浮点变量和整数相乘的结果。因此,我希望能够做的是:

template<unsigned long long T, double E>
class foo {
 SelectInteger<T*E>::type a;
}

但是由于模板不适用于浮点变量(请参阅此处(,因此我无法在模板中传递E。有没有其他方法可以将变量(在编译期间应该可用(传递给类?

使用 constexpr 函数怎么样?

我的意思是。。。如下内容

template <unsigned long long>
struct SelectInteger
 { using type = int; };
template <>
struct SelectInteger<0U>
 { using type = short; };
constexpr unsigned long long getSize (unsigned long long ull, double d)
 { return ull*d; }
template <unsigned long long T>
struct foo
 { typename SelectInteger<T>::type a; };
int main()
 {
   static_assert( std::is_same<short,
                     decltype(foo<getSize(1ULL, 0.0)>::a)>::value, "!");
   static_assert( std::is_same<int,
                     decltype(foo<getSize(1ULL, 1.0)>::a)>::value, "!!");
 }