值范围的模板专门化

Template specialization for a range of values

本文关键字:专门化 范围      更新时间:2023-10-16

我想写一个模板结构foo,这样foo<N>::value_type是最接近N的整数(四舍五入)。例如:foo<32>::value_type => uint32_tfoo<33>::value_type => uint64_tfoo<72>::value_type => uint64_t

要做到这一点,我需要一种优雅的方法来为一系列值提供foo的部分专门化,例如,1 <= N <= 8返回uint8_t等等。有没有一种方法可以做到这一点,而不必专门从0到64。

template<size_t N> struct select { typedef uint64_t result; };
template<> struct select<0> { typedef uint8_t result; };
template<> struct select<1> { typedef uint16_t result; };
template<> struct select<2> { typedef uint32_t result; };
template<size_t N>
struct foo
{
    enum{D = (N > 32 ? 3 : (N > 16 ? 2 : (N > 8 ? 1 : 0)))};
    typedef typename select<D>::result value_type;
    value_type value;
};

在c++11中可以使用std::conditional:

typedef 
    typename std::conditional<(N > 32), uint64_t,
    typename std::conditional<(N > 16), uint32_t,
    typename std::conditional<(N > 8), uint16_t, uint8_t>
    ::type>::type>::type value_type;

你可以决定哪一个是较难读的

@hansmaad答案是一个很好的答案,但我更喜欢使用(你猜怎么着?!)增加:

boost::uint_t<N>::least // N: bits

至少有N位的最小内置无符号整型。参数应该是一个正数。编译时错误参数的位数大于最大整数类型

模板参数需要是具体的,所以我不认为有任何方法可以避免对每个所需值进行专门化。