c++ - 如何获得枚举的基本类型?

标签 c++ templates c++11

声明如下:

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 的基础类型(即无符号)?

最佳答案

std::underlying_type 在 GCC 4.7 中可用,但在那之前您可以获得近似的 emulation with templates :

#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> {};
}

它不会为您提供确切的类型,但会为您提供具有相同大小和符号特征的类型。

关于c++ - 如何获得枚举的基本类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931378/

相关文章:

c++ - 为什么使用标准类型作为模板参数?

C++ 不需要的类型推导

c++ - 通过套接字 C++ 发送长字符串

c++ - 如何将函数指针的 std::vector 初始化为运算符重载?

c++ - 模板函数中需要什么类型的迭代器?

c++ - 在哪里定义/声明比较运算符的重载为库中的非成员函数?

C++11 可选模板类型参数?

c++11 - 包装函数的返回类型 C++11

c++ - 什么是 "rvalue reference for *this"?

c++ - 为什么 observer_ptr 在 move 后不归零?