【问题标题】:Template specialization for a range of values [duplicate]一系列值的模板特化[重复]
【发布时间】:2011-10-04 17:11:44
【问题描述】:

我希望编写一个模板结构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 的所有内容。

【问题讨论】:

  • 不会有直接的方法(就像 Mark 说的那样),但可能有一些巧妙的模板元编程技巧。好问题,等着看答案。

标签: c++ templates template-meta-programming


【解决方案1】:
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;
};

中你可以使用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;

您可以决定哪个可读性较差。

【讨论】:

  • 很好的答案。不过,枚举不应该是enum{D = (N &gt; 32 ? 3 : (N &gt; 16 ? 2 : (N &gt; 8 ? 1 : 0)))}; 吗?这是它的工作原理:ideone.com/OgXaz
  • 哦,哇,我以前也做过这个,但是这比我的版本简单得多!虽然我的有 bool(1)、char(2-8)、...、long long(33-64) 和 void(65+)
  • @filipe 谢谢你的完整测试,你是对的!
【解决方案2】:

@hansmaad 答案是一个不错的答案,但我更喜欢使用(猜猜是什么?!)Boost:

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

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

【讨论】:

  • 非常可爱,因为我在我的项目中使用了 boost,但它不能处理 foo::value_type 解析为最大可用整数的情况。
【解决方案3】:

模板参数需要具体,所以我认为没有任何方法可以避免专门针对每个必需的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多