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

前端 未结 4 673
清酒与你
清酒与你 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条回答
  •  Happy的楠姐
    2020-12-06 05:57

    You could use std::function<> and std::bind().

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

    These assumes you will use C++11. If you can't use C++11 but can use TR1, replace all std:: with std::tr1::. There is also a Boost implementation.

提交回复
热议问题