" in the second lambda, eve...">

Why 'this' is required, despite the fact that everything

Can someone explain to me why I should explicitly write "this->" in the second lambda, even if I captured everything?

Error message for completeness:

cannot call the member function 'result_t test :: get ()' without an object

#include <iostream> #include <functional> #include <algorithm> #include <vector> using result_t = std::function<void()>; struct test { bool noMore = false; result_t get() { return [this] { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); if(not noMore) { noMore = true; std::for_each(vec.begin(), vec.end(), [&](const auto& i) { auto value1 = this->get(); // compiles auto value2 = get(); // error }); } }; } }; int main() { test t; t.get()(); } 

Godbolt

+7
c ++ c ++ 14
source share
1 answer

This is a gcc error. From [expr.prim.lambda]:

The component operator of lambda expressions gives the body of the function (8.4) of the function call operator, but for search purposes by name (3.4), determining the type and value of this (9.3.2) and converting id expressions referring to non-static class members into member access expressions class, using (*this) (9.3.1), the compound statement is considered in the context of a lambda expression. [Example:

 struct S1 { int x, y; int operator()(int); void f() { [=]()->int { return operator()(this->x + y); // equivalent to S1::operator()(this->x + (*this).y) // this has type S1* }; } }; 

-end example]

In this case, get() should be equivalent to test::get() , and this fixed, so it is correctly formed. clang compiles the code as is. gcc compiles the code if you change i , which should be passed as int , and not as const auto& , which has nothing to do with get() search.

+9
source share

All Articles