如何得到枚举的基本类型
How do I get the fundamental type of an enum?
声明如下:
enum DrawBoldMode : unsigned
{
DBM_NONE = 0,
DBM_ITEM = 1<<0, // bold just the nearest line
DBM_SECTION = 1<<1, // bold all lines in the same section
DBM_LINETYPE = 1<<2, // bold all lines of the same line type
DBM_POINTAGE = 1<<3, // bold all lines of the same line type
};
我如何派生DrawBoldMode(即unsigned)的底层类型?
std::underlying_type
在GCC 4.7中可用,但在此之前,您可以使用模板获得近似模拟:
#include <tuple>
// This is a hack because GCC 4.6 does not support std::underlying_type yet.
// A specialization for each enum is preferred
namespace detail {
template <typename T, typename Acc, typename... In>
struct filter;
template <typename T, typename Acc>
struct filter<T, Acc> {
typedef typename std::tuple_element<0, Acc>::type type;
};
template <typename T, typename... Acc, typename Head, typename... Tail>
struct filter<T, std::tuple<Acc...>, Head, Tail...>
: std::conditional<sizeof(T) == sizeof(Head) && (T(-1) < T(0)) == (Head(-1) < Head(0))
, filter<T, std::tuple<Acc...,Head>, Tail...>
, filter<T, std::tuple<Acc...>, Tail...>
>::type {};
template <typename T, typename... In>
struct find_best_match : filter<T, std::tuple<>, In...> {};
}
namespace std {
template <typename E>
struct underlying_type : detail::find_best_match<E,
signed short,
unsigned short,
signed int,
unsigned int,
signed long,
unsigned long,
signed long long,
unsigned long long,
bool,
char,
signed char,
unsigned char,
wchar_t,
char16_t,
char32_t> {};
}
它不会给你确切的类型,但它会给你一个具有相同大小和签名特征的。
它应该作为std::underlying_type<DrawBoldMode>::type
可用。然而,我的编译器(GCC 4.6.1)似乎没有实现这一点。
我认为不可能用模板实现它,但我可能错了。
相关文章:
- 在有符号基础类型枚举的位域上溢出
- 在编译时将强类型枚举器转换为其基础类型?
- 如果 int 是"not within the enums range",为什么将 int 转换为强类型枚举会编译?
- 类型枚举的变量不是类型名称
- 强类型枚举的语法实现错误
- 枚举与强类型枚举
- 错误:T没有命名类型-用于使用强类型枚举的专门化
- 如何使用强类型枚举
- QT:将强类型枚举参数传递到插槽
- 在类定义中声明类型(枚举、结构等)会增加代码大小
- Visual Studio 11 (beta) 中的强类型枚举类
- 使用强类型枚举对类型和子类型进行建模
- 不允许将强类型枚举用作同一基础类型的参数
- 如何正确使用C++强类型枚举
- 带有强类型枚举的模板参数推导
- 是否可以在googleprotobuf中为类型(枚举或消息)定义一个别名
- C++中默认初始化的全局强类型枚举是什么
- std::is_signed不适用于强类型枚举:int
- 如何定义自定义值的类型?(枚举类型定义)
- 将强类型枚举传递给函数