In C , enums provide a convenient way to represent a set of named constants. However, when printing an enum value, the default behavior is to display its numeric representation.
Suppose we have an enum like this:
enum Errors { ErrorA = 0, ErrorB, ErrorC, };
If we try to print an enum value using std::cout:
Errors anError = ErrorA; std::cout << anError; // 0 will be printed
We will get the numeric value 0 instead of the text representation "ErrorA". This issue arises because std::cout lacks built-in support for converting enums to strings.
1. Using a Map
One approach is to create a map that associates each enum value with its text representation:
#include <map> #include <string_view> std::ostream& operator<<(std::ostream& out, const Errors value) { static const auto strings = [] { std::map<Errors, std::string_view> result; #define INSERT_ELEMENT(p) result.emplace(p, #p); INSERT_ELEMENT(ErrorA); INSERT_ELEMENT(ErrorB); INSERT_ELEMENT(ErrorC); #undef INSERT_ELEMENT return result; }; return out << strings[value]; }
2. Using an Array of Structures with Linear Search
Another option is to use an array of structures, each containing an enum value and its text representation, and then perform a linear search:
#include <string_view> std::ostream& operator<<(std::ostream& out, const Errors value) { #define MAPENTRY(p) {p, #p} const struct MapEntry { Errors value; std::string_view str; } entries[] = { MAPENTRY(ErrorA), MAPENTRY(ErrorB), MAPENTRY(ErrorC), {ErrorA, 0} //doesn't matter what is used instead of ErrorA here... }; #undef MAPENTRY const char* s = 0; for (const MapEntry* i = entries; i->str; i++) { if (i->value == value) { s = i->str; break; } } return out << s; }
3. Using switch/case
Finally, we can also use a switch/case statement:
#include <string> std::ostream& operator<<(std::ostream& out, const Errors value) { return out << [value] { #define PROCESS_VAL(p) case(p): return #p; switch(value) { PROCESS_VAL(ErrorA); PROCESS_VAL(ErrorB); PROCESS_VAL(ErrorC); } #undef PROCESS_VAL }; }
Testing the Solutions:
To test these solutions, we can create an executable using the following code:
#include <iostream> int main(int argc, char** argv) { std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC << std::endl; return 0; }
Running this executable should output the text representations of the enum values:
ErrorA ErrorB ErrorC
The above is the detailed content of How to Print C Enum Values as Text Without Using if/switch Statements?. For more information, please follow other related articles on the PHP Chinese website!