且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将lambda函数作为参数C ++传递

更新时间:2023-11-11 12:22:40

首先,如@tkausl所述,在将lambda作为参数传递时,您不应调用lambda,因为这样可以自动评估lambda并产生值(长在这种情况下会翻倍),但您的函数需要函数作为参数.

First, as mentioned by @tkausl, you should not call the lambdas when you pass them as parameters, because this way the are automatically evaluated and produce values(long doubles in this case), but your function expects a function as a parameter.

相反,您应该在被调用函数本身(在这种情况下为F)中调用作为参数给出的函数.

Instead you should call the functions you give as parameters in the called function itself(F in this case).

您可以使用std::function描述函数原型,从而避免使用难看的"函数指针.

You can use std::function to describe a function prototype, thus avoiding the "ugly" function pointers.

首先,您需要包括标准库中的<functional>头文件.

First you need to include the <functional> header file from the standard library.

然后您可以编写如下内容:

Then you can write something like this:

template <typename T>
using Func = std::function<T(T)>;

template <typename T>
T F(long double guess, long double tolerance, Func<T> f, Func<T> df); 

std::function<long double(long double)>中,括号中的类型表示函数参数的类型,括号前的类型表示函数原型的返回类型;

Where in std::function<long double(long double)> the type in the parentheses denote the type of the function arguments and the type before the parentheses is the return type of the function prototype;