我可以定义一个类型作为枚举的基础类型吗?像这样:
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
};
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/