如何从嵌套的 lambda 表达式函子类创建

How to create from nested lambda expression Functor classes

本文关键字:表达式 子类 创建 lambda 嵌套      更新时间:2023-10-16

我已经开始学习lambda表达式和嵌套lambda表达式:

    auto Suma=[](int x)->function<int(int)>
    {
        return [x](int y)
        {
            return x+y;
        };
    };
    auto Mult=[](function<int(int)>&f, int z)
    {
        return f(z)*2;
    };

我想创建 3 个函子类(为了更好地理解它是如何工作的(,它应该是 3 个类 Sum、Inner 和 Mult。

.h:

    class Suma
    {
    public:
        int operator()(int x);
    };
    class Inner
    {
        Suma function;
    public:
        Inner(int x);
        int operator()(int k);
    };
    class Mult
    {
    public:
        int operator()(Suma function,int z);
    };

。.cpp:

int Suma::operator()(int x)
{
return x;
}
Inner::Inner(int x)
{
    function.operator()(x);
}
int Inner::operator()(int k)
{
    return function.operator()+k;
}
int Mult::operator()(Suma function,int z)
{
    return (function.operator())*(2);
}

我面临的主要问题是尝试将函数从一个相关类包含到另一个相关类时。我不完全理解它如何通过类连接的主要思想。可以建议我它应该如何工作。

您的类不反映 lambda 的结构。

内部 lambda 返回一个函数,并将其参数添加到捕获中。所以你的Inner类不应该依赖于Suma,并定义如下:

// definition in .h
    class Inner
    {
        int myx; 
    public:
        Inner(int x);    // this represents the capture of the lambda
        int operator()(int k);  // this is the function of adding k to the catpture
    };
// implementation in .cpp
    Inner::Inner(int x) 
    {
        myx = x; 
    }
    int Inner::operator()(int k)
    {
        return myx + k;
    }

然后,苏玛将返回一个带有 x 集的Inner

// definition in .h
    class Suma
    {
    public:
        Inner operator()(int x);
    };
// implementation in .cpp
    Inner Suma::operator()(int x) 
    {
        return Inner(x); 
    };

使用lambdas,当您计算Suma(3) 时,您将获得一个函数,该函数接受一个整数并向其加3。 如果你评估Suma(3)(2)因此得到5。

使用模拟 lambda 的类,您将执行相同的操作:

Suma f;  // that is an object, like "auto suma"
cout << f(3)(2) <<endl;   // f(3) is in fact an object Inner(3) wich is then exectued with argument 2.  

这里有一个在线演示

您甚至可以通过让 Inner 成为嵌套的 Suma 类来更接近 lambda 的结构。

现在查看Mult类,似乎第一个参数不是Suma对象,而是调用Suma的结果(即其运算符((的返回类型(。 所以这是一个Inner. 因此,您可以按如下方式完成代码:

// definition in .h 
    class Mult {
    public:
        int operator()(Inner& function, int z);
    };
// implementation in .cpp
    int Mult::operator()(Inner& function, int z)
    {
        return (function(z))*(2);  // funtion(z) means function.operator()(z)
    }

顺便说一下,正如你在上面看到的,你不需要显式调用 operator((:只需提供括号之间的参数。