Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch/Case for multiple enum values

Tags:

c++

python

enums

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()
like image 397
Luca Fülbier Avatar asked Jan 07 '23 04:01

Luca Fülbier


1 Answers

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();
}
like image 86
Christian Hackl Avatar answered Jan 14 '23 23:01

Christian Hackl