根据浮点数选择最小整数类型
Choose smallest integer type based on a float
我正在尝试编写一个包含变量的类,该变量的类型将被选择为能够包含值的最小可能。
我的意思是:
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, "!!");
}
相关文章:
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 涉及旧式枚举和整数类型的重载解析
- 将字符串转换为整数类型T,检查是否存在溢出
- 整数文本太大,无法用任何整数类型表示--C++
- isdigit(c) - 字符或整数类型?
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- C++模板专用化 - 将其他整数类型委托给uint64_t
- 何时应使用 C++ 固定宽度整数类型,它们如何影响性能?
- 根据浮点数选择最小整数类型
- 为什么 QVariant 将字符类型视为整数类型
- 我们可以在整数类型的双指针中分配2D整数数组的地址吗?怎么可能
- 默认情况下,决定整数类型是唱歌或无符号的类型
- 是否可以根据类型是整数类型还是浮点类型重载模板函数
- 使用固定整数类型的安全性
- 如何使用条件来检查类型名 T 是否是 C++ 中浮点类型的整数类型
- C++文本整数类型
- 哪种整数类型可以安全且便携式用于始终保持指针值
- 检测整数类型变量上的空白输入
- 为什么对Chrono :: Nanseconds的表示类型是签名的整数类型
- 如何处理警告:从较小的整数类型int转换为int*