mojo1mojo2
mojo1mojo2

Reputation: 1130

When to use this for class function in lambda

When should this be used in a lambda to call a class member function? I have an example below, where hello(); is called without this but this->goodbye(); does:

#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;
}   

Is there any advantage to one way over the other?

Edit: The lambda for hello does not capture anything, yet it inherits functions that exist in the class scope. It cannot do this for members, why can it do this for functions?

Upvotes: 1

Views: 63

Answers (1)

Jarod42
Jarod42

Reputation: 217135

this is more explicit and more verbose.

but it might be also required with variables which hide member (capture or argument):

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.
};

Upvotes: 2

Related Questions