https://www.learncpp.com/cpp-tutorial/scoped-enumerations-enum-classes/
만약 아래와 같은 비교를 한다고 생각해보자
#include <iostream>
int main()
{
enum Color
{
red,
blue,
};
enum Fruit
{
banana,
apple,
};
Color color { red };
Fruit fruit { banana };
if (color == fruit) // The compiler will compare color and fruit as integers
std::cout << "color and fruit are equal\n"; // and find they are equal!
else
std::cout << "color and fruit are not equal\n";
return 0;
}
이러면 아이러니 하게도 color와 fruit 모두 if 문에서 int로 취급당해
color == fruit 가 true 판명이 된다
그래서 이러한 의도치 않은 동작을 피하기 위해 scope enumm이 도입된다
c++에서는 보통 enum class라고 불린다
enum class는
strongly typed (they won’t implicitly convert to integers) and strongly scoped (the enumerators are only placed into the scope region of the enumeration).
integer로 implicit하게 변환되지 않고 enumeration의 scope region에 위치하는 특성이 있다
키워드는 enum class 를 사용한다
#include <iostream>
int main()
{
enum class Color // "enum class" defines this as a scoped enumeration rather than an unscoped enumeration
{
red, // red is considered part of Color's scope region
blue,
};
enum class Fruit
{
banana, // banana is considered part of Fruit's scope region
apple,
};
Color color { Color::red }; // note: red is not directly accessible, we have to use Color::red
Fruit fruit { Fruit::banana }; // note: banana is not directly accessible, we have to use Fruit::banana
if (color == fruit) // compile error: the compiler doesn't know how to compare different types Color and Fruit
std::cout << "color and fruit are equal\n";
else
std::cout << "color and fruit are not equal\n";
return 0;
}
위에서 initialize를 할 때 보면 red에 direct로 접근할 수 없고 Color::red를 통해 접근한다
그리고 if문에서 compiler error가 발생한다
왜냐하면 compiler가 두개의 다른 타입인 Color와 Fruit를 비교하는 방법을 모르기 때문이다
#include <iostream>
int main()
{
enum class Color // "enum class" defines this as a scoped enum rather than an unscoped enum
{
red, // red is considered part of Color's scope region
blue,
};
std::cout << red; // compile error: red not defined in this scope region
std::cout << Color::red; // compile error: std::cout doesn't know how to print this (will not implicitly convert to int)
Color color { Color::blue }; // okay
return 0;
}
unscoped enum에서 처럼 그냥 red로 접근할 수가 없다
무조건 Color를 통해서 접근해야 한다
그리고 implicit하게 int로 conversion이 되지 않기 때문에 std::cout을 통해서 출력도 불가능하다
만약 type conversion이 필요하다면 static_cast를 통해서 가능하다
std::cout << static_cast<int>(color);
or
Pet pet{ static_cast<Pet>(input) };