如何将键映射到具有不同参数的函数?

是否有一种简单的方法将键映射到具有可变数量的参数(以及可能的可变返回类型)的函数。这就是我的意思。

//three functions,each variable number of args
void one_arg(int a) { std::cout << "a"; }
void two_args(int a,double b) { std::cout << "a\t" << "b\n"; }
void three_args(int a,double b,const char* c) { std::cout << "a\t" << "b\t" << "c\n"; }

std::function<void(int)> f_onearg = one_arg;
std::function<void(int,double)> f_twoargs = two_args;
std::function<void(int,double,const char*)> f_threeargs = three_args;

//now what??
template<typename... Args>
std::map<std::string,std::function<void(Args...)>> map_of_fun{ {"one",one_arg },{"two",two_args},{"three",three_args} };

//this is how i would like to call it
map_of_fun["one"](4);
map_of_fun["two"](4,9.34);

我在做什么错?它不起作用,错误在模板中的某个位置,但是我不知道在哪里。

Asp123Asp 回答:如何将键映射到具有不同参数的函数?

好的,用std :: bind解决问题

std::function<void()> f_onearg = std::bind(one_arg,10);
std::function<void()> f_twoargs = std::bind(two_args,10,3.14);
std::function<void()> f_threeargs = std::bind(three_args,3.14,"helo");


std::map<std::string,std::function<void()>> map_of_func{ {"one",f_onearg},{"two",f_twoargs},{"three",f_threeargs} };
map_of_func["one"]();
map_of_func["two"]();   
map_of_func["three"]();
本文链接:https://www.f2er.com/3048007.html

大家都在问