C++:函数指向具有可变数量参数的函数

jah*_*aho 17 c++ member-function-pointers function-pointers function

我试图找出一种方法,如何能够为具有不同数量的参数的函数分配函数指针.

我有一个while循环,它将许多不同的函数作为一个条件语句,所以我没有用完全相同的代码编写多个while循环,而是希望有一个带有函数指针的函数.所有功能都是格式化的bool f(...).我认为一些代码最能说明我的意思:

int a, b, c, d;
MyClass* my_class;

typedef bool (MyClass::*my_fun_t)();
my_fun_t my_fun;

if (condition1)
    my_fun = &MyClass::function_one();
else if (condition2)
    my_fun = &MyClass::function_two(a, b);
else if (condition3)
    my_fun = &MyClass::function_three(a, b, c);
else if (condition4)
    my_fun = &MyClass::function_four(a, b, c, d);

while ((my_class->*my_fun)()) 
{ ... }
Run Code Online (Sandbox Code Playgroud)

现在这显然不起作用,因为函数具有不同的签名.是否可以以类似的方式使其工作?我应该看一下functoids吗?

ken*_*ytm 7

你可以使用std::function<>std::bind().

#include <functional>

using std::placeholders::_1;

typedef std::function<bool(MyClass&)> 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)) { ... }
Run Code Online (Sandbox Code Playgroud)

这些假设您将使用C++ 11.如果您不能使用C++ 11但可以使用TR1,请将所有内容替换std::std::tr1::.还有一个Boost实现.


πάν*_*ῥεῖ 5

这对我有用:

#include <iostream>
#include <cstdarg>

using namespace std;

class MyInterface
{
public:
    virtual bool func(int argc, ...) = 0;
};

class MyImpl : public MyInterface
{
public:
    virtual bool func(int argc, ...);
};

bool MyImpl::func(int argc, ...)
{
    va_list varargs;
    va_start(varargs,argc);
    cout << "Arguments passed:" << endl;
    for(int i = 0; i < argc; ++i)
    {
        // expect double values
        double val = va_arg(varargs,double);
        cout << val << endl;
    }
    va_end(varargs);
    return true;
}

typedef bool (MyInterface::*MyFunc)(int, ...);

int main() {

    MyImpl impl;
    MyInterface* interface = &impl;
    MyFunc pfunc = &MyInterface::func;

    if(!(interface->*pfunc)(2,double(3.14),double(2.72)))
    {
        return 1;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Arguments passed:
3.14
2.72
Run Code Online (Sandbox Code Playgroud)

显然,您可以使用变量参数为(成员)函数声明和使用函数指针。