Mapping enums to strings is a common requirement in C development. The article provided earlier focuses on this issue and discusses potential solutions. The author initially suggests a simple method using a switch statement but expresses concerns about their C-like nature.
An alternative approach is to utilize a std::map
std::map<MyEnum, const char*> MyMap; map_init(MyMap) (eValue1, "A") (eValue2, "B") (eValue3, "C") ;
The map_init class facilitates the chaining of operator(), similar to operator<< on std::ostreams. The class uses a templated map_init_helper to provide a friendly interface for adding entries to any map or map-like structure.
Here's the implementation of the map_init class and helper:
templatestruct map_init_helper { T& data; map_init_helper(T& d) : data(d) {} map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value) { data[key] = value; return *this; } }; template map_init_helper map_init(T& item) { return map_init_helper (item); } The article also mentions boost::assign as an existing library that provides similar functionality. By using a map or map-init class, developers can easily convert enum values to corresponding strings for improved readability and usability.
The above is the detailed content of How Can I Efficiently Convert C Enums to Strings?. For more information, please follow other related articles on the PHP Chinese website!