python - 多个枚举值的开关/大小写

标签 python c++ enums

我有两个值,每个值都来自不同的枚举。我想检查这两者的允许组合,如果没有找到则执行默认操作。我能以某种方式对这两个值进行切换/大小写吗?我想避免使用多个 if/else 语句或遵循位掩码模式的枚举,只是因为我认为它们在代码中不如 switch/case 漂亮。

对于了解 python 的人,我基本上想要一个用 C++ 编写的 python 代码的解决方案:

val1 = "a"
val2 = 2
actions = {
    ("a", 1): func1,
    ("b" ,1): func2,
    ("a" ,2): func3,
    ("b" ,2): func4
}
action = actions.get((val1, val2), default_func)()
action()

最佳答案

想到带有 std::pair 键和 std::function 值的

std::map

更准确地说,您可以将函数对象映射到特定的枚举对象对。这是一个例子:

#include <map>
#include <functional>
#include <iostream>

enum class Enum1
{
    a, b, c
};

enum class Enum2
{
    one, two, three
};

int main()
{
    auto const func1 = [] { std::cout << "func1\n"; };
    auto const func2 = [] { std::cout << "func2\n"; };
    auto const func3 = [] { std::cout << "func3\n"; };
    auto const func4 = [] { std::cout << "func4\n"; };
    auto const default_func = [] { std::cout << "default\n"; };

    std::map<std::pair<Enum1, Enum2>, std::function<void()>> const actions =
    {
        {{ Enum1::a, Enum2::one }, func1 },
        {{ Enum1::b, Enum2::one }, func2 },
        {{ Enum1::a, Enum2::two }, func3 },
        {{ Enum1::b, Enum2::two }, func4 }
    };

    auto const val1 = Enum1::a;
    auto const val2 = Enum2::two;

    auto const action_iter = actions.find({ val1, val2 });
    auto const action = action_iter != actions.end() ? action_iter->second : default_func;
    action();
}

关于python - 多个枚举值的开关/大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36843000/

相关文章:

javascript - 服务器端串行通过 python Tornado 聊天

python - ValueError : Error when checking target: expected dense_10 to have shape (1, )但得到了形状为(19316,)的数组

python - matplotlib 2.0.0 的默认样式名称是什么?

C# 枚举索引问题

python - Google TaskQueue(拉)通过 API 插入任务

c++ - C++ 中的正则表达式抛出错误 "Invalid special open parenthesis."

c++ - 一个物体可以抛出自己吗?

c++ - 如何在没有任何依赖库的情况下在 Visual Studio 中构建 dll?

loops - 递归访问 HashMap 中的枚举

ruby-on-rails - 使用 Rails 枚举覆盖 bang 方法