如何从函数指针和参数中调用c ++中的函数

时间:2013-02-10 09:39:02

标签: c++ function-pointers invoke

我想通过具有未知参数的函数指针调用函数。存储输入参数和函数并稍后运行它。有点像php中的call_user_func_array

例如:

// example function definition
void foo(int arg1, const char *arg2,const char *arg3){
    //some other code
}
void bar(int arg1, int arg2){
    //some other code
}

// function definition
void store_function_call(int param,void *function,... args){
    // store param , function, and other arguments
    // in php save to global variable for use later
}
void call_later(){
    // execute stored param, function, arguments
    // in PHP use call_user_func_array
}
// use:
int main(){
    store_function_call(10,bar,4,5);
    // store_function_call(5,foo,5,"yyy","sss");

    call_later();
}

1 个答案:

答案 0 :(得分:2)

您可以通过一些模板元编程来完成您在C ++ 11中尝试做的事情:

#include <tuple>
#include <iostream>

template<int ...> struct seq {};
template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};
template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };

double foo(int x, float y, double z) {
  return x + y + z;
}

template <typename R, typename ...Args>
struct save_it_for_later {
  std::tuple<Args...> params;
  R (*func)(Args...);

  R call_later() {
    return callFunc(typename gens<sizeof...(Args)>::type());
  }

  template<int ...S>
  R callFunc(seq<S...>) {
    return func(std::get<S>(params) ...);
  }
};

template <typename R, typename ...Args>
save_it_for_later<R, Args...> store_function_call(R (*func)(Args...), Args&& ...args) {
  return save_it_for_later<R, Args...>{std::tuple<Args...>(std::forward<Args>(args)...), func};
}

int main() {
  auto saved = store_function_call(foo,1,1.f,1.);
  std::cout << saved.call_later() << "\n";
}

此答案已修改为与this answer to a similar question I asked中的方案相匹配。我添加了返回类型推导和帮助,以将类型推断为store_function_call

(我会使用std::forward_as_tuple而不是笨重的元组构造函数+ forward构造,但我测试的编译器没有那个)