C++:如何将一个函数(不知道其参数)传递给另一个函数?

标签 c++ pointers timer function-pointers parameter-passing

我正在尝试创建一个函数,该函数将存储和重复作为参数给定的另一个函数,持续特定时间或重复给定。 但是当你想将一个函数作为参数传递时,你必须事先知道它的所有参数。 如果我想将函数作为一个参数传递,而将参数作为另一个传递,我该怎么办?

void AddTimer(float time, int repeats, void (*func), params); // I know params has no type and that (*func) is missing parameters but it is just to show you what I mean

提前致谢

最佳答案

你能做的最好的就是使用 std::functionboost::function作为参数,连同 std::bindboost::bind好吧,将参数与函数绑定(bind):

void foo() { std::cout << "foo" << std::endl; }
void bar( int x ) { std::cout << "bar(" << x << ")" << std::endl; }
struct test {
   void foo() { std::cout << "test::foo" << std::endl; }
};
void call( int times, boost::function< void() > f )
{
   for ( int i = 0; i < times; ++i )
      f();
}
int main() {
   call( 1, &foo );                   // no need to bind any argument
   call( 2, boost::bind( &bar, 5 ) );
   test t;
   call( 1, boost::bind( &test::foo, &t ) ); // note the &t
}

请注意,传递完全通用的函数指针存在一些固有的错误:如何使用它?调用函数的主体看起来如何能够传递未知类型的未定义数量的参数?那就是bind模板解析时,它们会创建一个类仿函数,将函数指针(具体函数指针)与调用时要使用的参数的拷贝一起存储(注意示例中的 &t,以便复制指针而不是对象)。 bind 的结果是一个可以通过已知接口(interface)调用的仿函数,在这种情况下,它可以绑定(bind)在 function< void() > 中并且没有参数调用。

关于C++:如何将一个函数(不知道其参数)传递给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4837613/

相关文章:

c++ - 非静态成员变量创建类似于 C++ 中的静态单例创建

c++ - 存储坐标的最佳方式 : struct of uints or double?

c++ - 指向多维数组第 n 个元素的指针

c# - Windows 服务上的多个计时器未正确触发

android - 每 60 秒以编程方式 'press' 按钮

c++ - 改进我的四叉树设计?

c++ - 如何在 Ubuntu 14.04 中安装 Qt 3.3.8

指针数组中的 C++ 错误

c++ - c++中不同指针语法之间的语义差异?

java - 如何创建像电话一样的秒/毫秒计时器?