[英]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
. 我有一个函数
executor
,该函数executor
程序通过函数指针和一个通用函数origin
调用,我不会将带有不同参数a
和b
参数传递给该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 使用lambda函数
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 . 在http://ideone.com/rDKHC1上查看所有这些工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.