我以前有很多C#经验,但我是C++的新手.当我尝试使用lambda时,我已经看到了这个问题.
例如:
auto compare = [] (int i1, int i2) { return i1*2 > i2; }
Run Code Online (Sandbox Code Playgroud)
有没有办法用特定的类型定义lambda,而不是自动扣除?
我问这个是因为我想为我的班级定义一个普通的lambda.这个lambada将在多个地方使用,所以我不想多次定义它们.但是,'auto'只能用于静态成员,而另一方面,我想访问lambda中的非静态字段.
您可以使用std::function,但如果这不够高效,您可以编写一个函子对象,它类似于 lambda 在幕后所做的事情:
auto compare = [] (int i1, int i2) { return i1*2 > i2; }
Run Code Online (Sandbox Code Playgroud)
几乎与
struct Functor {
bool operator()(int i1, int i2) const { return i1*2 > i2; }
};
Functor compare;
Run Code Online (Sandbox Code Playgroud)
如果函子应该捕获上下文中的某些变量(例如“this”指针),则需要在函子内添加成员并在构造函数中初始化它们:
auto foo = [this] (int i) { return this->bar(i); }
Run Code Online (Sandbox Code Playgroud)
几乎与
struct Functor {
Object *that;
Functor(Object *that) : that(that) {}
void operator()(int i) const { return that->bar(i); }
};
Functor foo(this);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2922 次 |
| 最近记录: |