[英]function name as parameter in c++
假设我有 function:
double fun (int *a, int b)
{
//sth
}
我还有其他 function fun2
,我想将上面的 function 传递给它,如下所示:
fun2(fun);
如何定义fun2
以及如何使用其中作为参数传递的 function?
那么最简单的方法是使用模板(它将为您推断类型,无需挖掘 function 指针和公司):
template<class Funct>
double fun2(Funct my_funct){
my_funct( /*parameters of the function, or at least something that can be casted to the required types of the function parameters*/ );
}
简而言之,您“传递”了一个 function 指针,该指针可用作 function,因此使用operator()
调用它。
这将与定义了operator()(/*parameters of my_funct*/)
所有内容以及定义了该运算符的对象(例如,检查functors
)或可调用的函数和 lambdas 一起编译。
老式的方式(一个 function 指针):
void fun2(double (*fun)(int*, int));
C++11 及以后的方式:
#include <functional>
void fun2(std::function<double(int*, int)> fun);
您可以为此使用常规的旧 function 指针。 你可以给它起别名,使它看起来像 function 参数一样好一点。
using callback = double( * )( int* a, int b );
void fun2( callback cb )
{
// Invoke directly.
auto ret{ cb( nullptr, 0 ) };
// Or with 'invoke'.
ret{ std::invoke( cb, nullptr, 0 ) };
}
调用fun2
:
fun2( [ ]( auto ptr, auto value ) { return 1.0; } );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.