【问题标题】:how to invoke function in c++ from function pointer and arguments如何从函数指针和参数调用c++中的函数
【发布时间】:2013-02-10 09:39:02
【问题描述】:

我想通过具有未知参数的函数指针调用函数。存储输入参数和函数并稍后运行。 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();
}

【问题讨论】:

  • 你可能想使用 Boost::bind。

标签: c++ function-pointers invoke


【解决方案1】:

您可以通过一些模板元编程来完成您在 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 而不是笨重的元组构造函数+前向构造,但我测试的编译器没有)

【讨论】:

  • @seyed 您需要在编译器上启用 C++11。对于 gcc -std=c++0x 就足够了。
  • 我如何存储store_function_call的返回值的数组(或向量)?
  • @seyed - 你需要一些类型擦除。 C ++ 11 中的std::function 以方便的形式为您提供了准确的信息,例如std::vector&lt;std::function&lt;void ()&gt;&gt; stored_functions; stored_functions.push_back(store_function_call(foo, 1));
猜你喜欢
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 2016-03-14
  • 2011-01-29
  • 2013-03-31
  • 2021-12-21
相关资源
最近更新 更多