The C++14 (precisely, N4296) says with respect to enumerations, in 7.2:11:
Each enum-name and each unscoped enumerator is declared in the scope that immediately contains the enum-specifier.
Now what happens if a namespace N contains an opaque-enum-declaration of an enum E, and later the enumeration is fully declared from the global namespace? Shall we find its enumerators in the global namespace, or in the namespace N?
Of course, in order to opaque-declare an unscoped enumeration, it shall have a fixed underlying type. Consider the following piece of code.
namespace N { enum E : int; } enum N::E : int {A,B}; namespace N { int foo() { return int(::N::B); } } int bar() { //return int(::A); return int(A); }
The first line in bar
is commented out, because clang++ -std=c++14
says:
no member named 'A' in the global namespace; did you mean simply 'A'?
Gcc fails to compile both lines in bar(). So both gcc and clang declare the enumerations in the namespace N
.
So my questions are:
A
, B
be defined in the global namespace?bar
function, why ::A
does not refer to the enumerator, but simple A
does?::N::B
in the function N::foo
denotes the enumerator?EDIT 1: the original declaration was enum ::N::E : int {A,B};
, but gcc was not able to parse it (bug report), so I removed the leading colons to use enum N::E : int {A,B};
EDIT 2: the clang's behavior is a bug
An enumeration type declaration gives the name of the (optional) enumeration tag. And, it defines the set of named integer identifiers (called the enumeration set, enumerator constants, enumerators, or members). A variable of the enumeration type stores one of the values of the enumeration set defined by that type.
In an unscoped enum, the scope is the surrounding scope; in a scoped enum, the scope is the enum-list itself. In a scoped enum, the list may be empty, which in effect defines a new integral type. By using this keyword in the declaration, you specify the enum is scoped, and an identifier must be provided.
In C++ programming, enum or enumeration is a data type consisting of named values like elements, members, etc., that represent integral constants. It provides a way to define and group integral constants. It also makes the code easy to maintain and less complex.
Enum Class C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped. Class enum doesn't allow implicit conversion to int, and also doesn't compare enumerators from different enumerations.
The enumeration E is declared within the namespace N, even though its definition is set within the global namespace. As such, it can only be accessed in the scope of N.
The bar function should then be defined as:
int bar() { return int(N::A); //SAME AS --> return int(::N::A); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With