我有两个值,每个值都来自不同的枚举。我想检查这两者的允许组合,如果没有找到则执行默认操作。我能以某种方式对这两个值进行切换/大小写吗?我想避免使用多个 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/