Reputation: 2971
I know that the underlying type of an enum class should be an integral. Is it possible to define an enum class with a Base class reference as underlying type?
class CInt {
public:
CInt() = default;
virtual ~CInt() = default;
virtual void fun1() = 0;
virtual void fun2() = 0;
};
class A : public CInt {
A() : CInt() {};
~A() = default;
void fun1() {
std::cout << "A fun1" << std::endl;
}
void fun2() {
std::cout << "A fun2" << std::endl;
}
};
class B : public CInt {
B() : CInt() {};
~B() = default;
void fun1() {
std::cout << "B fun1" << std::endl;
}
void fun2() {
std::cout << "B fun2" << std::endl;
}
};
// the below code doesn't compile
enum class ClassType : CInt& {
A_Type, // class A object reference
B_Type // class B object reference
};
Upvotes: 0
Views: 66
Reputation: 51835
The token(s) between the :
(if present) and the opening {
in a scoped enum
declaration specifies what is called – in this Draft C++17 Standard – the type-specifier-seq:
10.2 Enumeration declarations [dcl.enum]
…
enum-base:
: type-specifier-seq
Further on in the same section, that type-specifier-seq is constrained as follows:
2 … The type-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored. …
Thus, as a reference type is not an integral type, it cannot be used as the "underlying type" of the enum
.
From the same Draft Standard, the definition of "integral type" is as follows:
6.7.1 Fundamental types [basic.fundamental]
…
7 Typesbool
,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. …
Note: The equivalent sections in a more-recent Draft Standard can be found here [dcl.enum]
and here [basic.fundamental]
.
Upvotes: 1