C++ std::function variable with varying arguments

后端 未结 6 1491
天涯浪人
天涯浪人 2020-12-28 09:12

In my callback system I want to store std::function (or something else) with varying arguments.

Example:

  1. I want to call void()
6条回答
  •  臣服心动
    2020-12-28 10:06

    The other answers are fine but I want to show my solution as well.

    It's a small header with which you can "elongate" function signatures. This allows you to do this (extract from the github example):

    int foo_1p(int a);
    int foo_2p(int a, int b);
    int foo_3p(int a, int b, int c);
    int foo_4p(int a, int b, int c, int d);
    int foo_5p(int a, int b, int c, int d, int e);
    int foo_6p(int a, int b, int c, int d, int e, int f);
    int foo_7p(int a, int b, int c, int d, int e, int f, std::string g);
    ...
    
    int main()
    {
       std::unordered_map> map;
       map["foo_1p"] = ex::bind(foo_1p, ph, ph, ph, ph, ph, ph);
       map["foo_2p"] = ex::bind(foo_2p, ph, ph, ph, ph, ph);
       map["foo_3p"] = ex::bind(foo_3p, ph, ph, ph, ph);
       map["foo_4p"] = ex::bind(foo_4p, ph, ph, ph);
       map["foo_5p"] = ex::bind(foo_5p, ph, ph);
       map["foo_6p"] = ex::bind(foo_6p, ph);
       map["foo_7p"] = foo_7p;
    
       for (const auto& f : map)
       {
           std::cout << f.first << " = " << f.second(1, 1, 1, 1, 1, 1, "101") << std::endl;
       }
    }
    

提交回复
热议问题