Docsity

C++11 Enums: Strongly-Typed Enums and Forward Declarations, Lecture notes of C programming

Partial preview of the text

Download C++11 Enums: Strongly-Typed Enums and Forward Declarations and more Lecture notes C programming in PDF only on Docsity!

C++ 11

ENUM FORWARD DECLARATIONS

STRONG ENUMS

7/13/2015 | Page Division

MITK C++ 11/14 STATUS

  • http://mitk.org/wiki/MITK_C++_11/14_Status

7/13/2015 | Page Division

UNSCOPED ENUMERATION

enum name { enumerator = constexpr , enumerator = constexpr , ... }

  • declares an unscoped enumeration type whose underlying type is not

fixed

Since C++ 11:

enum name : type { enumerator = constexpr , enumerator = constexpr , ... }

  • declares an unscoped enumeration type whose underlying type is fixed

7/13/2015 | Page Division EXAMPLE TRADITIONAL ENUMS enum Color { red, yellow, green= 20 , blue }; Color col = red; int n = blue; // n == 21 struct Foo { enum Direction { left='l', right='r' }; }; Foo x; int a = Foo::left; int b = x.left; int c = Foo::Direction::left; // allowed only in C++11 and later

7/13/2015 | Page Division EXAMPLE IMPLICIT CONVERSION 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 scoped enum to int conversion int n = static_cast(r); // OK, n = 21

7/13/2015 | Page Division EXAMPLE ENUM FORWARD DECLARATION

  • underlying type can be specified, so forward declaration is possible enum class Selection : unsigned char; void make_selection(Selection s) { } enum class Selection : unsigned char { None, Single, Multiple, };

7/13/2015 | Page Division

REFERENCES

  • http://mitk.org/wiki/MITK_C++_11/14_Status
  • http://en.cppreference.com/w/cpp/language/enum
  • http://www.cprogramming.com/tutorial/enum.html
  • http://stackoverflow.com/questions/12581064/enum-vs-

strongly-typed-enum