如何轻松地将 C++ 枚举映射到字符串

时间:2023-04-25
本文介绍了如何轻松地将 C++ 枚举映射到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在使用的一些库头文件中有一堆枚举类型,我想要一种将枚举值转换为用户字符串的方法,反之亦然.

I have a bunch of enum types in some library header files that I'm using, and I want to have a way of converting enum values to user strings - and vice-versa.

RTTI 不会为我做这件事,因为用户字符串"需要比枚举更具可读性.

RTTI won't do it for me, because the 'user strings' need to be a bit more readable than the enumerations.

一个蛮力的解决方案是一堆这样的函数,但我觉得这有点太像 C 了.

A brute force solution would be a bunch of functions like this, but I feel that's a bit too C-like.

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");
  }
}

我有一种使用模板的优雅解决方案的直觉,但我还不能完全理解它.

I have a gut feeling that there's an elegant solution using templates, but I can't quite get my head round it yet.

更新:感谢您的建议 - 我应该明确指出枚举是在第三方库标头中定义的,因此我不想更改它们的定义.

UPDATE: Thanks for suggestions - I should have made clear that the enums are defined in a third-party library header, so I don't want to have to change the definition of them.

我现在的直觉是避免使用模板并执行以下操作:

My gut feeling now is to avoid templates and do something like this:

char * MyGetValue(int v, char *tmp); // implementation is trivial

#define ENUM_MAP(type, strings) char * getStringValue(const type &T) 
 { 
 return MyGetValue((int)T, strings); 
 }

; enum eee {AA,BB,CC}; - exists in library header file 
; enum fff {DD,GG,HH}; 

ENUM_MAP(eee,"AA|BB|CC")
ENUM_MAP(fff,"DD|GG|HH")

// To use...

    eee e;
    fff f;
    std::cout<< getStringValue(e);
    std::cout<< getStringValue(f);

推荐答案

如果您希望枚举名称本身为字符串,请参阅 这篇文章.否则, std::map 会很好地工作.(将字符串文字复制到映射中的 std::strings 没有意义)

If you want the enum names themselves as strings, see this post. Otherwise, a std::map<MyEnum, char const*> will work nicely. (No point in copying your string literals to std::strings in the map)

对于额外的语法糖,这里是如何编写 map_init 类.目标是允许

For extra syntactic sugar, here's how to write a map_init class. The goal is to allow

std::map<MyEnum, const char*> MyMap;
map_init(MyMap)
    (eValue1, "A")
    (eValue2, "B")
    (eValue3, "C")
;

函数template map_init(T&) 返回一个 map_init_helper.map_init_helper<T> 存储一个 T&,并定义了微不足道的 map_init_helper&operator()(typename T::key_type const&, typename T::value_type const&).(从 operator() 返回 *this 允许链接 operator(),就像 operator<<< onstd::ostreams)

The function template <typename T> map_init(T&) returns a map_init_helper<T>. map_init_helper<T> stores a T&, and defines the trivial map_init_helper& operator()(typename T::key_type const&, typename T::value_type const&). (Returning *this from operator() allows the chaining of operator(), like operator<< on std::ostreams)

template<typename T> struct 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<typename T> map_init_helper<T> map_init(T& item)
{
    return map_init_helper<T>(item);
}

由于函数和辅助类是模板化的,您可以将它们用于任何地图或类似地图的结构.IE.它还可以将条目添加到 std::unordered_map

Since the function and helper class are templated, you can use them for any map, or map-like structure. I.e. it can also add entries to std::unordered_map

如果您不喜欢编写这些帮助程序,boost::assign 提供了开箱即用的相同功能.

If you don't like writing these helpers, boost::assign offers the same functionality out of the box.

这篇关于如何轻松地将 C++ 枚举映射到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:为什么模板参数推导在这里不起作用? 下一篇:C++ 函数模板偏特化?

相关文章

最新文章