Difference between revisions of "cpp/language/enum"
m (→Scoped enumerations: turn {{source}} into {{example}} (no "implicit conversion" needed)) |
m (fmt) |
||
Line 1: | Line 1: | ||
+ | <nowiki> | ||
{{title|Enumeration declaration}} | {{title|Enumeration declaration}} | ||
{{cpp/language/declarations/navbar}} | {{cpp/language/declarations/navbar}} |
Revision as of 04:49, 9 October 2023
{{title|Enumeration declaration}} {{cpp/language/declarations/navbar}} An ''enumeration'' is a distinct type whose value is restricted to a range of values (see below for details), which may include several explicitly named constants ("''enumerators''"). The values of the constants are values of an integral type known as the ''underlying type'' of the enumeration. An enumeration has the same {{rlp|sizeof|size}}, {{rlp|object#Object representation and value representation|value representation}}, and {{rlp|object#Alignment|alignment requirements}} as its underlying type. Furthermore, each value of an enumeration has the same representation as the corresponding value of the underlying type. An enumeration is (re)declared using the following syntax: {{sdsc begin}} {{sdsc|num=1|1= {{spar|enum-key attr}}{{mark optional}} {{spar|enum-head-name}}{{mark optional}} {{spar|enum-base}}{{mark optional}}<br>{{ttb|{}} {{spar|enumerator-list}}{{mark optional}} {{ttb|}<!---->}} }} {{sdsc|num=2|1= {{spar|enum-key attr}}{{mark optional}} {{spar|enum-head-name}}{{mark optional}} {{spar|enum-base}}{{mark optional}}<br>{{ttb|{}} {{spar|enumerator-list}} {{ttb|, }<!---->}} }} {{sdsc|num=3|notes={{mark since c++11}}|1= {{spar|enum-key attr}}{{mark optional}} {{spar|enum-head-name enum-base}}{{mark optional}} {{ttb|;}} }} {{sdsc end}} @1@ ''enum-specifier'', which appears in {{spar|decl-specifier-seq}} of the {{rlp|declarations|declaration}} syntax: defines the enumeration type and its enumerators. @2@ A trailing comma can follow the {{spar|enumerator-list}}. @3@ ''Opaque enum declaration'': defines the enumeration type but not its enumerators: after this declaration, the type is a complete type and its size is known. {{par begin}} {{par|{{spar|enum-key}}| {{rrev multi|rev1={{ttb|enum}} |since2=c++11|rev2=one of {{ttb|enum}}, {{ttb|enum class}}, or {{ttb|enum struct}}}}}} {{par|{{spar|attr}}|{{mark since c++11}} optional sequence of any number of {{rlp|attributes}}}} {{par|{{spar|enum-head-name}}| {{rrev multi|rev1=the name of the enumeration that's being declared, it can be omitted. |since2=c++11|rev2=the name of the enumeration that's being declared, optionally preceded by a {{spar|nested-name-specifier}}: sequence of names and scope-resolution operators {{tt|::}}, ending with scope-resolution operator. It can only be omitted in unscoped non-opaque enumeration declarations.<br> {{spar|nested-name-specifier}} may only appear if the enumeration name is present and this declaration is a redeclaration. For opaque enumeration declarations, {{spar|nested-name-specifier}} can only appear before the name of the enumeration in {{rlp|template specialization|explicit specialization declarations}}.<br> If {{spar|nested-name-specifier}} is present, the ''enum-specifier'' cannot refer to an enumeration merely inherited or introduced by a {{rlp|using declaration|using-declaration}}, and the ''enum-specifier'' can only appear in a namespace enclosing the previous declaration. In such cases, {{spar|nested-name-specifier}} cannot begin with a {{rlp|decltype}} specifier.}}}} {{par|{{spar|enum-base}}|{{mark since c++11}} colon ({{ttb|:}}), followed by a {{spar|type-specifier-seq}} that names an integral type (if it is cv-qualified, qualifications are ignored) that will serve as the fixed underlying type for this enumeration type}} {{par|{{spar|enumerator-list}}|comma-separated list of enumerator definitions, each of which is either simply a unique {{spar|identifier}}, which becomes the name of the enumerator, or a unique identifier with an initializer: {{spar|identifier}} {{ttb|{{=}}}} {{spar|constexpr}}. {{rev inl|since=c++17|In either case, the {{spar|identifier}} can be directly followed by an optional {{rlp|attributes|attribute specifier sequence}}.}}}} {{par end}} There are two distinct kinds of enumerations: ''unscoped enumeration'' (declared with the {{spar|enum-key}} {{ttb|enum}}) and ''scoped enumeration'' (declared with the {{spar|enum-key}} {{ttb|enum class}} or {{ttb|enum struct}}). ===Unscoped enumerations=== {{sdsc begin}} {{sdsc|num=1|1= {{ttb|enum}} {{spar|name}}{{mark optional}} {{ttb|{}} {{spar|enumerator}} {{ttb|1==}} {{spar|constexpr}} {{ttb|,}} {{spar|enumerator}} {{ttb|{{=}}}} {{spar|constexpr}} {{ttb|,}} ... {{ttb|}<!---->}} }} {{sdsc|num=2|notes={{mark since c++11}}|1= {{ttb|enum}} {{spar|name}}{{mark optional}} {{ttb|:}} {{spar|type}} {{ttb|{}} {{spar|enumerator}} {{ttb|1==}} {{spar|constexpr}} {{ttb|,}} {{spar|enumerator}} {{ttb|1==}} {{spar|constexpr}} {{ttb|,}} ... {{ttb|}<!---->}} }} {{sdsc|num=3|notes={{mark since c++11}}|1= {{ttb|enum}} {{spar|name}} {{ttb|:}} {{spar|type}} {{ttb|;}} }} {{sdsc end}} @1@ Declares an unscoped enumeration type whose underlying type is not fixed (in this case, the underlying type is an implementation-defined integral type that can represent all enumerator values; this type is not larger than {{c|int}} unless the value of an enumerator cannot fit in an {{c|int}} or {{c|unsigned int}}. If the {{spar|enumerator-list}} is empty, the underlying type is as if the enumeration had a single enumerator with value 0. If no integral type can represent all the enumerator values, the enumeration is ill-formed). @2@ Declares an unscoped enumeration type whose underlying type is fixed. @3@ Opaque enum declaration for an unscoped enumeration must specify the name and the underlying type. Each {{spar|enumerator}} becomes a named constant of the enumeration's type (that is, {{spar|name}}), visible in the enclosing scope, and can be used whenever constants are required. {{source|1= enum Color { red, green, blue }; Color r = red; switch(r) { case red : std::cout << "red\n"; break; case green: std::cout << "green\n"; break; case blue : std::cout << "blue\n"; break; } }} Each enumerator is associated with a value of the underlying type. When initializers are provided in the {{spar|enumerator-list}}, the values of enumerators are defined by those initializers. If the first enumerator does not have an initializer, the associated value is zero. For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one. {{source|1=enum Foo { a, b, c = 10, d, e = 1, f, g = f + c }; //a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12}} Values of unscoped enumeration type are {{rlp|implicit conversion#Integral promotion|implicitly-convertible}} to integral types. If the underlying type is not fixed, the value is convertible to the first type from the following list able to hold their entire value range: {{c|int}}, {{c|unsigned int}}, {{c|long}}, {{c|unsigned long}}, {{rev inl|since=c++11|{{c|long long}}, or {{c|unsigned long long}}, extended integer types with higher conversion rank (in rank order, signed given preference over unsigned)}}. If the underlying type is fixed, the values can be converted to their underlying type (preferred in {{rlp|overload resolution}}), which can then be {{rlp|implicit conversion#Integral promotion|promoted}}. {{source|1= enum color { red, yellow, green = 20, blue }; color col = red; int n = blue; // n == 21 }} Values of integer, floating-point, and enumeration types can be converted by {{rlpt|static_cast}} or {{rlp|explicit cast}}, to any enumeration type. If the underlying type is not fixed and the source value is out of range, the behavior is undefined. (The source value, as converted to the enumeration's underlying type if floating-point, is in range if it would fit in the smallest {{rlp|bit field|bit-field}} large enough to hold all enumerators of the target enumeration.) Otherwise, the result is the same as the result of {{rlp|implicit conversion}} to the underlying type. Note that the value after such conversion may not necessarily equal any of the named enumerators defined for the enumeration. {{source|1= enum access_t { read = 1, write = 2, exec = 4 }; // enumerators: 1, 2, 4 range: 0..7 access_t rwe = static_cast<access_t>(7); assert((rwe & read) && (rwe & write) && (rwe & exec)); access_t x = static_cast<access_t>(8.0); // undefined behavior since CWG 1766 access_t y = static_cast<access_t>(8); // undefined behavior since CWG 1766 enum foo { a = 0, b = UINT_MAX }; // range: [0, UINT_MAX] foo x = foo(-1); // undefined behavior since CWG 1766, // even if foo's underlying type is unsigned int }} The {{spar|name}} of an unscoped enumeration may be omitted: such declaration only introduces the enumerators into the enclosing scope: {{source|1=enum { a, b, c = 0, d = a + 2 }; // defines a = 0, b = 1, c = 0, d = 2}} When an unscoped enumeration is a class member, its enumerators may be accessed using class member access operators {{ttb|.}} and {{ttb|->}}: {{source|1= struct X { enum direction { left = 'l', right = 'r' }; }; X x; X* p = &x; int a = X::direction::left; // allowed only in C++11 and later int b = X::left; int c = x.left; int d = p->left; }} {{rrev|since=c++11| In the {{rlp|declarations#Specifiers|declaration specifiers}} of a {{rlp|class#Member specification|member declaration}}, the sequence :{{ttb|enum}} {{spar|enum-head-name}} {{ttb|:}} is always parsed as a part of enumeration declaration: {{source| struct S { enum E1 : int {}; enum E1 : int {}; // error: redeclaration of enumeration, // NOT parsed as a zero-length bit-field of type enum E1 }; enum E2 { e1 }; void f() { false ? new enum E2 : int(); // OK: 'int' is NOT parsed as the underlying type } }} }} ===Scoped enumerations=== {{rrev|since=c++11| {{sdsc begin}} {{sdsc|num=1|1= {{ttb|enum struct{{!}}class}} {{spar|name}} {{ttb|{}} {{spar|enumerator}} {{ttb|1==}} {{spar|constexpr}} {{ttb|,}} {{spar|enumerator}} {{ttb|1==}} {{spar|constexpr}} {{ttb|,}} ... {{ttb|}<!---->}} }} {{sdsc|num=2|1= {{ttb|enum struct{{!}}class}} {{spar|name}} {{ttb|:}} {{spar|type}} {{ttb|{}} {{spar|enumerator}} {{ttb|1==}} {{spar|constexpr}} {{ttb|,}} {{spar|enumerator}} {{ttb|1==}} {{spar|constexpr}} {{ttb|,}} ... {{ttb|}<!---->}} }} {{sdsc|num=3|1= {{ttb|enum struct{{!}}class}} {{spar|name}} {{ttb|;}} }} {{sdsc|num=4|1= {{ttb|enum struct{{!}}class}} {{spar|name}} {{ttb|:}} {{spar|type}} {{ttb|;}} }} {{sdsc end}} @1@ declares a scoped enumeration type whose underlying type is {{c|int}} (the keywords {{c|class}} and {{c|struct}} are exactly equivalent) @2@ declares a scoped enumeration type whose underlying type is {{spar|type}} @3@ opaque enum declaration for a scoped enumeration whose underlying type is {{c|int}} @4@ opaque enum declaration for a scoped enumeration whose underlying type is {{spar|type}} Each {{spar|enumerator}} becomes a named constant of the enumeration's type (that is, {{spar|name}}), which is contained within the scope of the enumeration, and can be accessed using scope resolution operator. There are no implicit conversions from the values of a scoped enumerator to integral types, although {{rlpt|static_cast}} may be used to obtain the numeric value of the enumerator. {{example |code= #include <iostream> int main() { enum class Color { red, green = 20, blue }; Color r = Color::blue; switch(r) { case Color::red : std::cout << "red\n"; break; case Color::green: std::cout << "green\n"; break; case Color::blue : std::cout << "blue\n"; break; } // int n = r; // error: no implicit conversion from scoped enum to int int n = static_cast<int>(r); // OK, n = 21 std::cout << n << '\n'; // prints 21 } }} }} {{anchor|enum_relaxed_init_cpp17}} {{rrev|since=c++17| An enumeration can be initialized from an integer without a cast, using {{rlp|list initialization}}, if all of the following are true: * The initialization is direct-list-initialization. * The initializer list has only a single element. * The enumeration is either scoped or unscoped with underlying type fixed. * The conversion is non-narrowing. This makes it possible to introduce new integer types (e.g. {{tt|SafeInt}}) that enjoy the same existing calling conventions as their underlying integer types, even on ABIs that penalize passing/returning structures by value. {{source|1= enum byte : unsigned char {}; // byte is a new integer type; see also std::byte (C++17) byte b{42}; // OK as of C++17 (direct-list-initialization) byte c = {42}; // error byte d = byte{42}; // OK as of C++17; same value as b byte e{-1}; // error struct A { byte b; }; A a1 = {<!---->{42}<!---->}; // error (copy-list-initialization of a constructor parameter) A a2 = {byte{42}<!---->}; // OK as of C++17 void f(byte); f({42}); // error (copy-list-initialization of a function parameter) enum class Handle : std::uint32_t { Invalid = 0 }; Handle h{42}; // OK as of C++17 }} }} {{rrev|since=c++20| ===Using-enum-declaration=== {{sdsc begin}} {{sdsc|notes={{mark since c++20}}| {{ttb|using enum}} {{spar|nested-name-specifier}}{{mark optional}} {{spar|name}} {{ttb|;}} }} {{sdsc end}} {{spar|nested-name-specifier}}{{mark optional}} {{spar|name}} must name a non-{{rlp|dependent name#Dependent types|dependent}} enumeration type. The enumeration declarations are found by ordinary {{rlp|qualified lookup|qualified}} or {{rlp|unqualified lookup|unqualified}} lookup, depending on whether {{spar|nested-name-specifier}} is present. A using-enum-declaration introduces the enumerator names of the named enumeration as if by a {{rlp|using declaration|using-declaration}} for each enumerator. When in class scope, a using-enum-declaration adds the enumerators of the named enumeration as members to the scope, making them accessible for member lookup. {{source|1= enum class fruit { orange, apple }; struct S { using enum fruit; // OK: introduces orange and apple into S }; void f() { S s; s.orange; // OK: names fruit::orange S::orange; // OK: names fruit::orange } }} Two using-enum-declarations that introduce two enumerators of the same name conflict. {{source|1= enum class fruit { orange, apple }; enum class color { red, orange }; void f() { using enum fruit; // OK // using enum color; // error: color::orange and fruit::orange conflict } }} }} ===Notes=== {{ftm begin|core=1|std=1|comment=1}} {{ftm|std=C++17|value=201411L|__cpp_enumerator_attributes|{{rlp|attributes|Attributes}} for enumerators}} {{ftm|std=C++20|value=201907L|__cpp_using_enum|[[#Using-enum-declaration|{{tt|using enum}}]]}} {{ftm end}} ===Example=== {{example |code= #include <cstdint> #include <iostream> // enum that takes 16 bits enum smallenum: std::int16_t { a, b, c }; // color may be red (value 0), yellow (value 1), green (value 20), or blue (value 21) enum color { red, yellow, green = 20, blue }; // altitude may be altitude::high or altitude::low enum class altitude: char { high = 'h', low = 'l', // trailing comma only allowed after CWG 518 }; // the constant d is 0, the constant e is 1, the constant f is 3 enum { d, e, f = e + 2 }; // enumeration types (both scoped and unscoped) can have overloaded operators std::ostream& operator<<(std::ostream& os, color c) { switch(c) { case red : os << "red"; break; case yellow: os << "yellow"; break; case green : os << "green"; break; case blue : os << "blue"; break; default : os.setstate(std::ios_base::failbit); } return os; } std::ostream& operator<<(std::ostream& os, altitude al) { return os << static_cast<char>(al); } // The scoped enum (C++11) can be partially emulated in earlier C++ revisions: enum struct E11 { x, y }; // since C++11 struct E98 { enum { x, y }; }; // OK in pre-C++11 namespace N98 { enum { x, y }; } // OK in pre-C++11 struct S98 { static const int x = 0, y = 1; }; // OK in pre-C++11 void emu() { std::cout << (static_cast<int>(E11::y) + E98::y + N98::y + S98::y) << '\n'; // 4 } namespace cxx20 { enum class long_long_long_name { x, y }; void using_enum_demo() { std::cout << "C++20 `using enum`: __cpp_using_enum == "; switch (auto rnd = []{return long_long_long_name::x;}; rnd()) { #if defined(__cpp_using_enum) using enum long_long_long_name; case x: std::cout << __cpp_using_enum << "; x\n"; break; case y: std::cout << __cpp_using_enum << "; y\n"; break; #else case long_long_long_name::x: std::cout << "?; x\n"; break; case long_long_long_name::y: std::cout << "?; y\n"; break; #endif } } } int main() { color col = red; altitude a; a = altitude::low; std::cout << "col = " << col << '\n' << "a = " << a << '\n' << "f = " << f << '\n'; cxx20::using_enum_demo(); } |p=true |output= col = red a = l f = 3 C++20 `using enum`: __cpp_using_enum == 201907; x }} ===Defect reports=== {{dr list begin}} {{dr list item|wg=cwg|dr=377|std=C++98|before=the behavior was unspecified when no integral<br>type can represent all the enumerator values|after=the enumeration is ill-<br>formed in this case}} {{dr list item|wg=cwg|dr=518|std=C++98|before=a trailing comma was not allowed after the enumerator list|after=allowed}} {{dr list item|wg=cwg|dr=1514|std=C++11|before=a redefinition of enumeration with fixed underlying type<br>could be parsed as a bit-field in a class member declaration|after=always parsed as a redefinition}} {{dr list item|wg=cwg|dr=1638|std=C++11|before=grammar of opaque enumeration declaration<br>prohibited use for template specializations|after=nested-name-specifier<br>permitted}} {{dr list item|wg=cwg|dr=1766|std=C++98|before=casting an out-of-range value to an enumeration<br>without fixed underlying type had an unspecified result|after=the behavior is undefined}} {{dr list item|wg=cwg|dr=1966|std=C++11|before=the resolution of {{cwg|1514}} made the {{tt|:}}<br>of a conditional expression part of {{spar|enum-base}}|after=only apply the resolution to<br>member declaration specifiers}} {{dr list item|wg=cwg|dr=2156|std=C++11|before=enum definitions could define<br>enumeration types by using-declarations|after=prohibited}} {{dr list item|wg=cwg|dr=2157|std=C++11|before=the resolution of {{cwg|1966}} did<br>not cover qualified enumeration names|after=covered}} {{dr list item|wg=cwg|dr=2530|std=C++98|before=an enumerator list could contain multiple<br>enumerators with the same identifier|after=prohibited}} {{dr list item|wg=cwg|dr=2590|std=C++98|before=the size, value representation and alignment requirements<br>of an enumeration did not depend on its underlying type|after=all of them are identical to<br>those of the underlying type}} {{dr list item|wg=cwg|dr=2621|std=C++20|before=it was unclear how the enumeration names<br>are found in using-enum-declarations|after=they are found using<br>ordinary name lookup}} {{dr list end}} ===See also=== {{dsc begin}} {{dsc inc|cpp/types/dsc is_enum}} {{dsc inc|cpp/types/dsc is_scoped_enum}} {{dsc inc|cpp/types/dsc underlying_type}} {{dsc inc|cpp/utility/dsc to_underlying}} {{dsc see c|c/language/enum|Enumerations|nomono=true}} {{dsc end}} {{langlinks|ar|de|es|fr|it|ja|pt|ru|zh}}