vendredi 16 juillet 2021

How to use one map to store different function

My colleague wrote a very long switch-case function as below:

void func(int type, int a, int b) {
    std::string str = "hello";
    switch (type) {
        case 1: {
            func1(a, b);
            break;
        }
        case 2: {
            func2(a, b, str);
            break;
        }
        // hundreds of cases...
    }
}

I want to change this terrible funciton because it has too many cases.

Good new is that each case only invokes one function, which must use a and b as its first and second parameters. Bad news is that some of them may need the third parameter.

I'm thinking if I can use a std::map<int, std::function<void(int, int, ...)>> to store all of functions in the cases but it's not working. It doesn't seem that std::function could accept a variadic function.

It there some other way to do so?

Aucun commentaire:

Enregistrer un commentaire