C++: Function pointer to functions with variable number of arguments

前端 未结 4 678
清酒与你
清酒与你 2020-12-06 04:57

I\'m trying to figure out a way of how to be able to assign a function pointer to functions with different number of arguments.

I have a while loop which takes a nu

4条回答
  •  忘掉有多难
    2020-12-06 05:33

    You want std::function, a polymorphic function object, and std::bind to create function objects by binding arguments to the parameters of other functors.

    If you can't use C++11, then boost::function and boost::bind are equivalent, although slightly more restrictive.

    std::function my_fun;
    
    if (condition1)
        my_fun = std::bind(&MyClass::function_one, my_class);
    else if (condition2)
        my_fun = std::bind(&MyClass::function_two, my_class, a, b);
    else if (condition3)
        my_fun = std::bind(&MyClass::function_three, my_class, a, b, c);
    else if (condition4)
        my_fun = std::bind(&MyClass::function_four, my_class, a, b, c, d);
    
    while (my_fun()) 
    { ... }
    

提交回复
热议问题