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

yun*_*tmr 6 c++ lambda templates

我正在将 lambda 函数 R1 和 R2 传递给我的模板函数 F。但是,我不确定我这样做是否正确。

函数 F 应该使用来自主函数的所有参数并执行相关计算(牛顿法近似根)。

我是使用模板函数的新手。因此,任何帮助将不胜感激。

//main.cpp
    #include <iostream>
    #include "Funct.h"
    using namespace std;

    int main()
    {

        auto f1 = [](long double x) { return (x * x) - 2; };
        auto f2 = [](long double x) { return (2 * x);
        auto RV1 = F<long double>(1.0L,1.0E-20L,f1(1.0L),f2(1.0L));
        return 0;


    }

    //Funct.h
    #include <iostream>
    #include<cmath>
    template<typename T> T F(long double guess, long double tolerance,T ((*f)(const T x)), T((*df)(const T x)));
    template<typename T> T F(long double guess, long double tolerance,T ((*f)(const T x)), T((*df)(const T x)))
    {

    }
Run Code Online (Sandbox Code Playgroud)

Pet*_*and 7

首先,正如@tkausl 所提到的,当您将 lambda 作为参数传递时,不应调用它们,因为这样会自动评估并生成值(在这种情况下为 long double),但您的函数需要一个函数作为参数。

相反,您应该调用您在被调用函数本身中作为参数提供的函数(在本例中为 F)。

你可以用std::function一个函数原型来描述,从而避免“丑陋”的函数指针。

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

然后你可以这样写:

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); 
Run Code Online (Sandbox Code Playgroud)

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

  • 由于 `F` 已经是一个模板,最好的解决方案是通过两个类型模板参数传递 `f` 和 `df`,从而避免从 `std::function` 中删除类型的开销,这里不会带来太多。 (3认同)

Jar*_*d42 6

你可能会使用:

template <typename F1, typename F2>
long double F(long double guess,
              long double tolerance,
              F1 f,
              F2 der)
{
    f(4.2); // call function
    der(4.2);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

用法类似于:

auto f = [](long double x) { return (x * x) - 2; };
auto derived = [](long double x) { return 2 * x; };
auto RV1 = F(1.0L, 1.0E-20L, f, derived);
Run Code Online (Sandbox Code Playgroud)