值范围的模板专门化
Template specialization for a range of values
我想写一个模板结构foo
,这样foo<N>::value_type
是最接近N
的整数(四舍五入)。例如:foo<32>::value_type => uint32_t
、foo<33>::value_type => uint64_t
、foo<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位的最小内置无符号整型。参数应该是一个正数。编译时错误参数的位数大于最大整数类型
模板参数需要是具体的,所以我不认为有任何方法可以避免对每个所需值进行专门化。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 是否可以对零模板参数进行模板专门化
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 如何为多个整数值范围专门化C++模板?
- 如何在类范围内定义/专门化type_trait
- 值范围的模板专门化
- GCC错误:在非命名空间范围内显式专门化