当应this
在拉姆达被用来调用类的成员函数?我有一个例子所示,其中hello();
被称为无this
但this->goodbye();
的作用:
#include <iostream>
class A
{
void hello() { std::cout << "hello" << std::endl; }
void goodbye() { std::cout << "goodbye" << std::endl; }
public:
void greet()
{
auto hi = [this] () { hello(); }; // Don't need this.
auto bye = [this] () { this->goodbye(); }; // Using this.
hi();
bye();
}
};
int main()
{
A a;
a.greet();
return 0;
}
是否有任何优势,比其他的一种方式?
编辑:对于hello
拉姆达没有捕获任何,但它继承了存在于类范围的功能。它不能为会员做到这一点,为什么它的功能做到这一点?
this
更加明确和更详细。
但它可能还需要与隐藏成员(捕获或参数)变量:
auto goodbye = [](){}; // Hide method
auto bye = [=] (int hello) {
this->goodbye(); // call method
goodbye(); // call above lambda.
this->hello(); // call method
std::cout << 2 * hello; // show int parameter.
};