c++ - 自定义枚举基础类型

标签 c++ enums

我可以定义一个类型作为枚举的基础类型吗?像这样:

struct S {
    S(int i) : value(i) {}
    operator int() { return value; }

    int value;
};

enum E : S {
    A, B, C
};

错误信息告诉我S必须是整数类型。我尝试像下面这样专门化 std::is_integral,但似乎在这种情况下,“整数类型”确实意味着基本类型之一。

namespace std {
    template<>
    struct is_integral<S> : public true_type {};
}

那么,使用任何版本的 C++,是否有办法使自定义类型作为整数类型假冒?

最佳答案

Can I define a type to use as the underlying type of an enumeration?

您只能使用整数类型来定义 enum,不能使用任何旧类型。

例如,您可以使用

enum E : char {
    A, B, C
};

表示 E 的值将是 char 类型。但是你不能使用

enum E : S {
    A, B, C
};

来自C++11 Standard, 3.9.1/7 :

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type.

关于c++ - 自定义枚举基础类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44618373/

相关文章:

c++ - 如何在 OpenCV 中对图像进行阈值处理?

c++ - 如何在基类的子级中强制使用私有(private)构造函数

c++ - 自定义条件语句?这可能吗?

c# - 决定需要哪个子类的最佳方法

Java - 枚举通配符

c# - 使用枚举实现层次结构的最佳 C# 模式是什么?

c++ - win32api SendMessage 不能在 WM_CREATE 之外工作

C++ 析构函数和内存分配,以及未定义的行为

c# - 能够通过反射分配无效的枚举值

c# - C#中的字符串值枚举