通过编译时值推断整数的类型

Deducing the type of an integer by its compiletime value

本文关键字:整数 类型 编译      更新时间:2023-10-16

使用 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>;