简体   繁体   中英

Wrapping functions in c++

I have a function executor which is called with function pointer and a general function origin which I wan't to pass with different parameters a and b to the executor . How can it be done?

Here is what I have tried so far:

#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);
}

You can wrap a function using several methods. It is easier if you make executor a function template.

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

Use a global function

float a = 1;
float b = 2;

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

void call_executor_global1() {
  executor(wrapped);
}

Use a lambda function

float a = 1;
float b = 2;

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

Use a functor

float a = 1;
float b = 2;

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

See all of them working at http://ideone.com/rDKHC1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM