用于多个枚举值的开关/案例

Luc*_*ier 3 c++ python 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()
Run Code Online (Sandbox Code Playgroud)

Chr*_*ckl 5

std::map想到了std::pair钥匙和std::function价值观.

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

#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();
}
Run Code Online (Sandbox Code Playgroud)