Home >Backend Development >C++ >How to Efficiently Map C Enums to Strings?
When utilizing enums defined in third-party library headers, it becomes necessary to establish a mechanism for converting enum values to user-defined strings and vice versa.
A straightforward approach involves creating a series of functions:
enum MyEnum {VAL1, VAL2,VAL3}; String getStringFromEnum(MyEnum e) { switch e { case VAL1: return "Value 1"; case VAL2: return "Value 2"; case VAL1: return "Value 3"; default: throw Exception("Bad MyEnum"); } }
This method, however, lacks elegance and resembles a C-style approach.
A more sophisticated approach utilizes templates:
std::map<MyEnum, char const*> MyMap; //... MyMap.insert(std::make_pair(VAL1, "Value 1")); //... char const* enumString = MyMap[e];
This method provides a clean and efficient mapping mechanism.
For syntactic convenience, the following helper class can be used:
template<typename T> struct map_init_helper { map_init_helper(T& d) : data(d) {} T& data; map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value) { data[key] = value; return *this; } }; template<typename T> map_init_helper<T> map_init(T& item) { return map_init_helper<T>(item); }
With this helper, the mapping can be accomplished as follows:
std::map<MyEnum, char const*> MyMap; map_init(MyMap) (VAL1, "Value 1") (VAL2, "Value 2") (VAL3, "Value 3");
This simplified syntax eliminates the need for verbose insert statements.
The above is the detailed content of How to Efficiently Map C Enums to Strings?. For more information, please follow other related articles on the PHP Chinese website!