如何从嵌套的 lambda 表达式函子类创建
How to create from nested lambda expression Functor classes
我已经开始学习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((:只需提供括号之间的参数。
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 避免在C++中重复子类定义
- 将QOpenGLWidget子类转换为使用Metal而不是OpenGL的子类是否可行?
- 如何初始化矢量的模板化子类
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 使用子类覆盖基类中定义的函数
- 子类地址等于虚拟基类地址?
- 将子类方法声明为基类的友元
- C++子类共享变量?
- 如何检查模板专用化是否是基本模板的子类?
- 仅让特定类'Fabric'构造类'Foo'及其所有子类的实例
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 如何在C++子类中访问父类的私有变量
- 如何从嵌套的 lambda 表达式函子类创建