【问题标题】:How to map keys to functions with different arguments?如何将键映射到具有不同参数的函数?
【发布时间】:2019-11-22 21:45:26
【问题描述】:

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

//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);

我做错了什么?不行,错误在模板的某个地方,但我不知道在哪里。

【问题讨论】:

    标签: stdmap std-function


    【解决方案1】:

    好的,用 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, 10, 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"]();
    

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 2015-03-25
      • 2020-02-01
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      相关资源
      最近更新 更多