我有两个值,每个值来自不同的枚举。我想检查这两者的允许组合,如果没有找到,请执行默认操作。我可以在这两个值上进行切换/切换吗?我想避免使用多个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::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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句