Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom enum underlying type

Tags:

c++

enums

Can I define a type to use as the underlying type of an enumeration? Something like this:

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

    int value;
};

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

The error message tells me that S must be an integral type. I have tried to specialize std::is_integral like the following, but it seems that in this context, "integral type" really means one of the fundamental types.

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

So, using any version of C++, is there a way to make a custom type pass off as an integral type?

like image 726
Nelfeal Avatar asked Jun 18 '17 18:06

Nelfeal


1 Answers

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

You can only use integral types to define enums, not any old type.

For example, you can use

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

to indicate the value of E will be of type char. But you can't use

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

From the 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.

like image 143
R Sahu Avatar answered Sep 25 '22 03:09

R Sahu