C : Enum 値をテキストとして出力
Enum 型は、定数のセットをシンボル名で表す便利な方法を提供します。デフォルトでは、列挙型は整数値として表されます。ただし、列挙値に関連付けられた実際のテキストを表示する必要がある状況では、デフォルトの動作は適切ではない可能性があります。
例を考えてみましょう。
enum Errors { ErrorA = 0, ErrorB, ErrorC, }; Errors anError = ErrorA; std::cout << anError; // Outputs "0"
この例では、 3 つの可能な値を持つ Errors 列挙型があります: ErrorA、ErrorB、および ErrorC。ここで、ErrorA の数値は 0 です。 anError 変数を出力しようとすると、
if/switch ステートメントに頼らずにこの問題を解決するには、いくつかの方法を使用できます。
1.マップの使用:
#include <map> #include <string_view> // Define a map to associate enum values with their string representations std::map<Errors, std::string_view> errorStrings = { {ErrorA, "ErrorA"}, {ErrorB, "ErrorB"}, {ErrorC, "ErrorC"}, }; // Overload the `<<` operator to print the string representation std::ostream& operator<<(std::ostream& out, const Errors value) { out << errorStrings[value]; return out; }
このメソッドでは、オーバーロードされた <<演算子は、errorStrings マップ内の列挙値に関連付けられた文字列表現を検索し、それを出力します。
2.構造体の配列の使用:
#include <string_view> // Define a struct to store enum values and string representations struct MapEntry { Errors value; std::string_view str; }; // Define an array of structures MapEntry entries[] = { {ErrorA, "ErrorA"}, {ErrorB, "ErrorB"}, {ErrorC, "ErrorC"}, }; // Overload the `<<` operator to perform a linear search and print the string representation std::ostream& operator<<(std::ostream& out, const Errors value) { for (const MapEntry& entry : entries) { if (entry.value == value) { out << entry.str; break; } } return out; }
このメソッドは、構造体の配列を使用して列挙値とその文字列表現を保存します。線形検索が実行され、指定された列挙値に一致する文字列が検索されます。
3. switch/case の使用:
#include <string> // Overload the `<<` operator to print the string representation using `switch/case` std::ostream& operator<<(std::ostream& out, const Errors value) { switch (value) { case ErrorA: out << "ErrorA"; break; case ErrorB: out << "ErrorB"; break; case ErrorC: out << "ErrorC"; break; } return out; }
このメソッドでは、オーバーロードされた <<演算子は switch/case ステートメントを使用して、指定された列挙値の適切な文字列表現を直接出力します。
以上がC の Enum 値のテキスト表現を印刷するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。