yeze322
yeze322

Reputation: 713

Failed to call class member function in C++ lambda expression

//==== 1 ====
string func1(string x1, string x2){
    return x1 + x2;
}
auto lambda1 = [](string x1, string x2){cout << func1(x1,x2);};

//==== 2 ====
class Test{
public:
    string func2(string x1, string x2){
        return x1 + x2;
    }
    void tst(){
        auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};
    }
};

lambda1 is right. But lambda2 got an error (under g++ 4.8):

error: 'this' was not captured for this lambda function
         auto lambda2 = [](string x1, string x2){cout << func2(x1,x2);};

What's the right way to call a member function in lambda?

Upvotes: 1

Views: 1569

Answers (2)

syntagma
syntagma

Reputation: 24304

The compiler gives you the answer you are looking for:

error: 'this' was not captured for this lambda function

You need to provide a this capture inside [] brackets:

auto lambda2 = [this](string x1, string x2){cout << func2(x1,x2);};

Without it, the compiler would not know the context of the variables. Note that both x1 and x2 will be copied.

Read more on lambda captures here.

Upvotes: 3

R Sahu
R Sahu

Reputation: 206567

In the lambda function under Test::tst(), you have a call to func2. That call cannot be completed unless this is captured by the lambda function.

void tst(){
    auto lambda2 = [this](string x1, string x2){cout << this->func2(x1,x2);};
}

should do it.

Upvotes: 0

Related Questions