C ++:具有可变数量参数的函数的函数指针 [英] C++: Function pointer to functions with variable number of arguments

查看:228
本文介绍了C ++:具有可变数量参数的函数的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我有一个while循环,它接受一些不同的函数作为一个条件语句,所以,而不是写多个while循环与完全相同的代码里面我想有一个带有一个函数指针。所有的函数都是格式 bool f(...)。我认为一些代码将最好地说明我的意思:

I have a while loop which takes a number of different functions as a conditional statement, so instead of writing multiple while loops with exactly the same code inside I'd like to have one with a function pointer. All the functions are of format bool f(...). I think some code will best illustrate what I mean:

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)()) 
{ ... }

现在这显然不工作,因为函数有不同的签名。它是否可能使它工作在类似的方式?是functoid我应该看看吗?

Now this obviously doesn't work because the functions have different signatures. Is it at all possible to make it work in a similar fashion? Are functoids something I should look at?

推荐答案

您可以使用 std :: function<> code> std :: bind()。

You could use std::function<> and 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)) { ... }

假设你将使用C ++ 11。如果你不能使用C ++ 11但是可以使用TR1,用 std :: tr1 :: std :: $ c>。还有 Boost实施

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.

这篇关于C ++:具有可变数量参数的函数的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆