模板结构体的静态const成员的不同值
Different values of a static const member of a template struct
我正在尝试制作一个小的元编程结构,它生成width
位的位掩码,将shift
位向左移动(主要用于学习目的)。下面的代码触发警告C4293(移位计数负或太大,未定义的行为)在vc++ 15对mask<64>::value;
,因为它仍然触发第二个分支的三元操作符-即使它不应该影响值本身。有什么更好、更干净的方法来实现这个目标呢?
// Bitmask of 'width' bits shifted 'shift' bits to the left
// For instance, mask<16,8> := 0x00FFFF00
template <uint8_t width, uint8_t shift=0>
struct mask {
static const uintmax_t value = (width >= (sizeof(uintmax_t)<<3)) ?
(~0 << shift) : (((uintmax_t(1)<<width)-1) << shift) ;
mask()=delete;
};
// A bitmask for a type, for instance, 0xFF for uint8_t
template <class T>
struct typeMask {
static const uintmax_t value = mask<sizeof(T)<<3>::value;
typeMask()=delete;
};
您希望避免编译条件的冗余分支width >= (sizeof(uintmax_t)<<3)
。我家里只有gcc 5.1和clang 3.6但是我希望vc++ 2015也能让你这样做:
#include <cstdint>
#include <type_traits>
template <uint8_t width, uint8_t shift=0, typename Enable = void>
struct mask;
template <uint8_t width, uint8_t shift> struct
mask<width,shift,typename std::enable_if<(width >= (sizeof(uintmax_t)<<3))>::type>
{
static const uintmax_t value = (~0 << shift);
mask()=delete;
};
template <uint8_t width, uint8_t shift> struct
mask<width,shift,typename std::enable_if<(width < (sizeof(uintmax_t)<<3))>::type>
{
static const uintmax_t value = (((uintmax_t(1)<<width)-1) << shift);
mask()=delete;
};
template <class T>
struct typeMask {
static const uintmax_t value = mask<sizeof(T)<<3>::value;
typeMask()=delete;
};
顺便说一下,编译mask<64>::value
, clang抱怨:
warning: in-class initializer for static data member is not a constant expression; folding it to a constant is a GNU extension [-Wgnu-folding-constant]
static const uintmax_t value = (~0 << shift);
~~~~^~~~~~~~~
您可以通过将~0
替换为~uintmax_t(0)
来纠正它的抱怨。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 私有类型的静态常量成员
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 添加静态constexpr成员是否会更改结构/类的内存映射
- 静态数据成员模板专用化的实例化点在哪里
- 在派生类中绑定非静态模板化成员函数
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 枚举成员与静态 int 成员?
- 使用静态成员声明类时遇到问题
- C++ 模板类型的静态 lambda 成员的构造
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 成员静态回调函数的外部"C"
- 成员静态函数中的C++静态变量
- 将pthread_mutex_t和pthread_cond_t作为类成员静态变量的任何缺点
- 初始化私有成员静态常量数组