通过编译时值推断整数的类型
Deducing the type of an integer by its compiletime value
使用 C++14、17 或 20,我将两个模板参数传递给模板化类:TSize 和 MaxSize。
TSize 是 MaxSize 的类型。显然,两者都在编译时是已知的。TSize 需要足够大以适合 MaxSize。
template <typename TSize = uint8_t, TSize MaxSize = 15>
class Foo {};
我怎样才能通过 MaxSize 的值自动推导出 TSize,那么我只需设置 MaxSize 的值即可自动获得它?即:
if MaxSize<256 -> TSize=uint8_t
if MaxSize<65536 && MaxSize>255 -> TSize=uint16_t
非常感谢您的帮助!
你可以使用这样的东西:
template<uintmax_t n>
using FittingUIntT = std::conditional_t<
n <= UINT8_MAX, uint8_t, std::conditional_t<
n <= UINT16_MAX, uint16_t, std::conditional_t<
n <= UINT32_MAX, uint32_t, uint64_t
>>>;
演示
可以使用std::conditional
根据编译时条件在两种类型之间进行选择。如果你不想改变Foo
你需要一些间接的方法来为Foo
选择正确的类型(也许部分专业化也可以(:
#include<type_traits>
template <typename TSize = uint8_t, TSize MaxSize = 15>
class Foo {};
template <unsigned value>
using Size_t_impl = typename std::conditional<(value > 255),uint16_t,uint8_t>::type;
template <unsigned value>
using FooIndirect = Foo< Size_t_impl<value>,value>;
相关文章:
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 涉及旧式枚举和整数类型的重载解析
- 将字符串转换为整数类型T,检查是否存在溢出
- 整数文本太大,无法用任何整数类型表示--C++
- isdigit(c) - 字符或整数类型?
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- C++模板专用化 - 将其他整数类型委托给uint64_t
- 何时应使用 C++ 固定宽度整数类型,它们如何影响性能?
- 根据浮点数选择最小整数类型
- 为什么 QVariant 将字符类型视为整数类型
- 我们可以在整数类型的双指针中分配2D整数数组的地址吗?怎么可能
- 默认情况下,决定整数类型是唱歌或无符号的类型
- 是否可以根据类型是整数类型还是浮点类型重载模板函数
- 使用固定整数类型的安全性
- 如何使用条件来检查类型名 T 是否是 C++ 中浮点类型的整数类型
- C++文本整数类型
- 哪种整数类型可以安全且便携式用于始终保持指针值
- 检测整数类型变量上的空白输入
- 为什么对Chrono :: Nanseconds的表示类型是签名的整数类型
- 如何处理警告:从较小的整数类型int转换为int*