mercredi 27 mai 2020

Insert in unordered map when expanding a macro in global scope

I have a macro that creates functions which are then called from an executable via the function name in command line arguments. A minimal example is:

#include <iostream>

#define MAKE_FUNCTION(func_name, custom_message) \
void func_name(){std::cout << #custom_message << std::endl;}

MAKE_FUNCTION(func_foo, "foo called")
MAKE_FUNCTION(func_bar, "bar called")

std::function<void()> get_function_from_string(std::string func_string){
    if(func_string == "func_foo")
        return func_foo;
    else if(func_string == "func_bar")
        return func_bar;
}

int main(int argc, char* argv[]) {
    get_function_from_string(argv[1])();
}

This is now run with

$./a.out func_foo
"foo called"

I want to do this without the help of the get_function_from_string function. For this I tried creating a static unordered map:

#include <iostream>
#include <unordered_map>

static std::unordered_map<std::string, std::function<void()> > global_map;

#define MAKE_FUNCTION(func_name, custom_message) \
void func_name(){std::cout << #custom_message << std::endl;} \
global_map[func_name] = func_name;

MAKE_FUNCTION(func_foo, "foo called")
MAKE_FUNCTION(func_bar, "bar called")

int main(int argc, char* argv[]) {
    global_map[argv[1]]();
}

But this does not compile saying:

$./a.out func_foo
error: C++ requires a type specifier for all declarations
MAKE_FUNCTION(func_bar, "bar called")

Is there a convenient way to do this?

Aucun commentaire:

Enregistrer un commentaire