型の安全性のために、C++ でenumクラスを使用することを推奨している人が何人かいると聞きました。
しかし、それは本当にどういう意味ですか?
C++ には次の 2 種類がありenum
ます。
enum class
エスenum
_それらを宣言する方法のいくつかの例を次に示します。
enum class Color { red, green, blue }; // enum class
enum Animal { dog, cat, bird, human }; // plain enum
2つの違いは何ですか?
enum class
es - 列挙子の名前は列挙型に対してローカルであり、それらの値は暗黙的に他の型に変換されませんenum
(別のor などint
)
Plain enum
s - 列挙子の名前が列挙型と同じスコープにあり、それらの値が暗黙的に整数やその他の型に変換される場合
例:
enum Color { red, green, blue }; // plain enum
enum Card { red_card, green_card, yellow_card }; // another plain enum
enum class Animal { dog, deer, cat, bird, human }; // enum class
enum class Mammal { kangaroo, deer, human }; // another enum class
void fun() {
// examples of bad use of plain enums:
Color color = Color::red;
Card card = Card::green_card;
int num = color; // no problem
if (color == Card::red_card) // no problem (bad)
cout << "bad" << endl;
if (card == Color::green) // no problem (bad)
cout << "bad" << endl;
// examples of good use of enum classes (safe)
Animal a = Animal::deer;
Mammal m = Mammal::deer;
int num2 = a; // error
if (m == a) // error (good)
cout << "bad" << endl;
if (a == Mammal::deer) // error (good)
cout << "bad" << endl;
}
enum class
バグにつながる可能性のある驚きが少ないため、.es を優先する必要があります。
列挙は、一連の整数値を表すために使用されます。
のclass
後のキーワードenum
は、列挙が厳密に型指定され、その列挙子のスコープが指定されていることを指定します。このようにenum
して、クラスは定数の偶発的な誤用を防ぎます。
例えば:
enum class Animal{Dog, Cat, Tiger};
enum class Pets{Dog, Parrot};
ここでは、Animal と Pets の値を混在させることはできません。
Animal a = Dog; // Error: which DOG?
Animal a = Pets::Dog // Pets::Dog is not an Animal
明示的に言及されていないことの 1 つ - スコープ機能により、列挙型とクラス メソッドに同じ名前を付けるオプションが提供されます。例えば:
class Test
{
public:
// these call ProcessCommand() internally
void TakeSnapshot();
void RestoreSnapshot();
private:
enum class Command // wouldn't be possible without 'class'
{
TakeSnapshot,
RestoreSnapshot
};
void ProcessCommand(Command cmd); // signal the other thread or whatever
};