按名称获取枚举值 [英] Get enum value by name

查看:192
本文介绍了按名称获取枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举,其中包含数百个条目。

I have an enumeration, which contains hundreds of entries.

我会越来越枚举作为一个字符串的值。有没有什么办法将字符串转换为一个枚举值?否则,我将最终使用数以百计的if语句。

I will be getting the value of the enumeration as a string. Is there any way to convert the string into an enum value? Otherwise, I will end up using hundreds of if statements.

考虑

enum Colors { Red, Green, Blue, Yellow ... } there are more than 100 entries

我会得到红楼梦在一个字符串变量,

String color = "Red"; // "Red" would be generated dynamically.

通常我们访问枚举以下列方式,
颜色::红色颜色::蓝色等...
有没有什么办法,使我们可以在这样的东西像这样的访问:

Normally we access the enum in the following way, Colors::Red, Colors::Blue etc... is there any way in which we can access it in a way something like this:

Colors::color; // i.e enumtype::stringVariable

在这里的许多职位,它给了我们可以使用的地图,但同样在构造图,我们将使用数百个,如果 s结尾了。

In many posts here, it’s given that we can use map, but again while constructing map we will end up in using hundreds of ifs.

有什么办法避免这种情况?

Is there any way to avoid this?

推荐答案

下面是这样做的一个C的方式,类似于帕迪C ++的地图。宏保证的名称和相应的枚举捆绑在一起。

Here's a C way of doing it, similar to Paddy's C++ map. The macro guarantees that the name and corresponding enum are tied together.

enum Colors { NoColor, Red, Green, Blue, Yellow };

enum Colors get_color(const char *s)
{
    const struct {
        char *name;
        enum Colors color;
    } colormap[] = {
#define Color(x) {#x, x}
        Color(Red),
        Color(Green),
        Color(Blue),
        Color(Yellow)
#undef Color
    };
    for (size_t i = 0; i < sizeof colormap / sizeof colormap[0]; ++i) {
        if (!strcmp(s, colormap[i].name)) {
            return colormap[i].color;
        }
    }
    return NoColor;
}



修改
正如@ SH1在评论中建议(现已消失),你可以使用X-宏来定义的颜色列表。这避免了限定两次列表。下面是使用X宏改写上面的例子 - 由于SH1的提示:


EDIT As @sh1 suggested in a comment (which has now gone), you could use an X-macro to define the list of colors. This avoids defining the list twice. Here's the above example rewritten using an X-macro - thanks to sh1 for the hint:

#define COLORS  X(Red), X(Green), X(Blue), X(Yellow),

enum Colors {
    NoColor, 
#define X(x) x
    COLORS
#undef X
};

enum Colors get_color(const char *s)
{
    const struct {
        char *name;
        enum Colors color;
    } colormap[] = {
#define X(x) {#x, x}
        COLORS
#undef X
    };
...etc

这篇关于按名称获取枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆