I have got two values, each one from a different enum. I want to check for a allowed combination of these two and perform a default action if none is found. Can i somehow do a switch/case on both of these values? I would like to avoid multiple if/else statements, or enums that follow a bit-mask pattern, simply because i think they are not as pretty in code as a switch/case.
For the people knowing python, i basically want a solution for this python code in C++:
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
with std::pair
keys and std::function
values comes to mind.
More precisely, you can map function objects to specific pairs of enum objects. Here is an example:
#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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With