Search code examples
c++if-statementhashmap

Is there any alternative to using if walls instead of something else in C++?


I'm doing some C++ and my app accepts subcommands, for example ./my_app test 123.

I'm semi-new to C++ and I can't find anything on the internet so I don't know haha.

For example in python I'd do:

#!/usr/bin/env python3

import sys

def test(num):
    print(f"Test {num}")

subcommands = {"test": test}

subcommands[sys.argv[1](sys.argv[2])

any C++ eq to this? if so, should I use it or stick to if-else_if-else?


Solution

  • Have a look at std::map/std::unordered_map, for example:

    #include <iostream>
    #include <map>
    #include <string>
    
    void test(const std::string &value) {
        std::cout << "Test " << value << std::endl;
    }
    
    using cmdFuncType = void(*)(const std::string &);
    
    const std::map<std::string, cmdFuncType> subcommands = {
        {"test": &test}
    };
    
    int main(int argc, char* argv[]) {
        if (argc != 3) {
            std::cerr << "usage: program command value" << std::endl;
            return 0;
        }
    
        auto iter = subcommands.find(argv[1]);
        if (iter == subcommands.end()) {
            std::cerr << "unknown command: " << argv[1] << std::endl;
            return 0;
        }
    
        iter->second(argv[2]);
        return 0;
    }