[英]Wrapping functions in c++
我有一個函數executor
,該函數executor
程序通過函數指針和一個通用函數origin
調用,我不會將帶有不同參數a
和b
參數傳遞給該executor
。 如何做呢?
到目前為止,這是我嘗試過的:
#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);
}
您可以使用多種方法包裝函數。 如果將執行程序設為功能模板會更容易。
template <typename F>
void executor(F f) {
float x = 1.;
std::cout << f(x) << std::endl;
}
使用全局功能
float a = 1;
float b = 2;
float wrapped(float x) {
return original(x,a,b);
}
void call_executor_global1() {
executor(wrapped);
}
使用lambda函數
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());
}
在http://ideone.com/rDKHC1上查看所有這些工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.