Is there a simple way to convert C++ enum to string?

后端 未结 30 2766
我在风中等你
我在风中等你 2020-11-22 10:37

Suppose we have some named enums:

enum MyEnum {
      FOO,
      BAR = 0x50
};

What I googled for is a script (any language) that scans all

30条回答
  •  梦谈多话
    2020-11-22 11:04

    Not so long ago I made some trick to have enums properly displayed in QComboBox and to have definition of enum and string representations as one statement

    #pragma once
    #include 
    
    namespace enumeration
    {
    
       struct enumerator_base : boost::noncopyable
       {
          typedef
             boost::unordered_map
             kv_storage_t;
          typedef
             kv_storage_t::value_type
             kv_type;
          kv_storage_t const & kv() const
          {
             return storage_;
          }
    
          LPCWSTR name(int i) const
          {
             kv_storage_t::const_iterator it = storage_.find(i);
             if(it != storage_.end())
                return it->second.c_str();
             return L"empty";
          }
    
       protected:
          kv_storage_t storage_;
       };
    
       template
       struct enumerator;
    
       template
       struct enum_singleton : enumerator_base
       {
          static enumerator_base const & instance()
          {
             static D inst;
             return inst;
          }
       };
    }
    
    #define QENUM_ENTRY(K, V, N)  K, N storage_.insert(std::make_pair((int)K, V));
    
    #define QBEGIN_ENUM(NAME, C)   \
    enum NAME                     \
    {                             \
       C                          \
    }                             \
    };                            \
    }                             \
    
    #define QEND_ENUM(NAME) \
    };                     \
    namespace enumeration  \
    {                      \
    template<>             \
    struct enumerator\
       : enum_singleton< enumerator >\
    {                      \
       enumerator()        \
       {
    
    //usage
    /*
    QBEGIN_ENUM(test_t,
       QENUM_ENTRY(test_entry_1, L"number uno",
       QENUM_ENTRY(test_entry_2, L"number dos",
       QENUM_ENTRY(test_entry_3, L"number tres",
    QEND_ENUM(test_t)))))
    */
    

    Now you've got enumeration::enum_singleton::instance() able to convert enums to strings. If you replace kv_storage_t with boost::bimap, you will also be able to do backward conversion. Common base class for converter was introduced to store it in Qt object, because Qt objects couldn't be templates

    Previous appearance

提交回复
热议问题