Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++中的包函数_C++ - Fatal编程技术网

C++中的包函数

C++中的包函数,c++,C++,我有一个用函数指针调用的函数执行器和一个通用函数原点,我不想用不同的参数a和b传递给执行器。怎样才能做到呢 以下是我迄今为止所尝试的: #include <iostream> void executor(float (*f)(float)) { float x = 1.; std::cout << (*f)(x) << std::endl; } float original(float x,float a,float b) { return a

我有一个用函数指针调用的函数执行器和一个通用函数原点,我不想用不同的参数a和b传递给执行器。怎样才能做到呢

以下是我迄今为止所尝试的:

#include <iostream>

void executor(float (*f)(float)) {
  float x = 1.;
  std::cout << (*f)(x) << std::endl;
}

float original(float x,float a,float b) {
  return a*x + b;
}

//// Works as expected

float a = 1;
float b = 2;

float wrapped(float x) {
  return original(x,a,b);
}

void call_executor_global() {
  executor(wrapped);
}

//// FIRST TRY

// void call_executor_func(float a, float b) {

//   float wrapped(float x) {
//     return original(x,a,b);
//   }
//   executor(wrapped);
// }

//// SECOND TRY

// struct Wrapper {
//   float a;
//   float b;

//   float func(float x) {
//     return original(x,a,b);
//   }
// };

// void call_executor_struct(float a, float b) {

//   Wrapper wrapped;
//   wrapped.a = a;
//   wrapped.b = b;

//   executor(wrapped.func);

// }


int main()
{
  call_executor_global();
  // call_executor_func(1,2);
  // call_executor_struct(1,2);
}

可以使用多种方法包装函数。如果将executor设置为函数模板,则更容易

template <typename F>
void executor(F f) {
  float x = 1.;
  std::cout << f(x) << std::endl;
}
使用lambda函数

使用函子


查看所有这些函数的工作情况。

使用比原始函数指针更好。您可能希望查看std::bind或使用lambdas,而不是编写包装函数。您不能使用executor的签名。你能改变它吗?在现实生活中,executor是从外部库加载的。传递一个int来指定有多少个参数和一个指向一个浮点数组的指针怎么样?所以如果我把库函数包装成函数模板,我可以用functor调用它,是这样吗?这看起来对我来说是可行的:啊,看起来在模板函数中,我不会得到传递到外部库的函数指针:/@JānisErdmanis,在这种情况下,您唯一的选择是创建一个全局函数,作为您希望调用的函数的包装器。在C中,是否可以在函数中局部更改gloabal变量a和b?
float a = 1;
float b = 2;

float wrapped(float x) {
  return original(x,a,b);
}

void call_executor_global1() {
  executor(wrapped);
}
float a = 1;
float b = 2;

void call_executor_global2() {
  executor([](float x) {return original(x, a, b);});
}
float a = 1;
float b = 2;

void call_executor_global3() {
   struct wrapper
   {
      float operator()(float x) { return original(x, a, b); }
   };
  executor(wrapper());
}