Home >Backend Development >C++ >How to Efficiently Map C Enums to Strings?

How to Efficiently Map C Enums to Strings?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 01:22:12543browse

How to Efficiently Map C   Enums to Strings?

How to Easily 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.

Standard Approach

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.

Template-Based Solution

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.

map_init Helper Class

For syntactic convenience, the following helper class can be used:

template<typename T> struct map_init_helper
{
    map_init_helper(T&amp; d) : data(d) {}
    T&amp; data;
    map_init_helper&amp; operator() (typename T::key_type const&amp; key, typename T::mapped_type const&amp; value)
    {
        data[key] = value;
        return *this;
    }
};

template<typename T> map_init_helper<T> map_init(T&amp; 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn