一系列值的模板特化

Fre*_*den 7 c++ templates template-meta-programming

我希望编写一个模板结构foo,这foo<N>::value_type是最接近大小的整数(向上舍入)N.例如foo<32>::value_type => uint32_t,foo<33>::value_type => uint64_tfoo<72>::value_type => uint64_t.

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

han*_*aad 15

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;
};
Run Code Online (Sandbox Code Playgroud)

您可以使用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;
Run Code Online (Sandbox Code Playgroud)

您可以决定哪一个不太可读.

  • 很好的答案.枚举不应该是'枚举{D =(N> 32?3 :( N> 16?2:(N> 8?1:0)))};`,但是?这是它的工作:http://ideone.com/OgXaz (2认同)

Ara*_*raK 7

@hansmaad答案是一个很好的答案,但我更愿意使用(猜猜是什么?!)提升:

boost::uint_t<N>::least // N: bits
Run Code Online (Sandbox Code Playgroud)

最小的内置无符号整数类型,至少有N位.参数应为正数.如果参数大于最大整数类型中的位数,则会产生编译时错误.