C++ 如何在c+中调用函数+;来自函数指针和参数

C++ 如何在c+中调用函数+;来自函数指针和参数,c++,function-pointers,invoke,C++,Function Pointers,Invoke,我想通过具有未知参数的函数指针调用函数。存储输入参数和函数,稍后再运行。php中的call\u user\u func\u 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 } // funct

我想通过具有未知参数的函数指针调用函数。存储输入参数和函数,稍后再运行。php中的
call\u user\u func\u 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();
}

您可以使用一点模板元编程来完成在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";
}
#包括
#包括
模板结构seq{};
模板结构gens:gens{};
模板结构gens{typedef seq type;};
双foo(整数x,浮点y,双z){
返回x+y+z;
}
模板
结构保存\u it\u以备以后使用{
std::tuple。我添加了返回类型推断和一个助手来推断类型,作为
store\u函数\u调用


(我本来会使用元组构造器+正向构造器来代替笨重的元组构造器,但我测试的编译器没有这个构造器)

您可能想使用Boost::bind。@seyed您需要在编译器上启用C++11。对于gcc
-std=C++0x
就足够了。我如何存储数组(或向量)
store\u function\u call
?@seyed-您需要一些类型的擦除。C++11中的
std::function
以一种方便的形式为您提供了准确的返回值,例如
std::vector stored\u functions;stored\u functions.push_back(store\u function\u call(foo,1));