Issue: passing a generic lambda (to a template function) that captures this
and calls a member function of this
without an explicit this->
does not compile on gcc. If the lambda is not generic, or if the lambda is not passed to any other function but called in place, it compiles withoit an explicit this->
. Clang is cool with the code in all situations.
Time for another round of clang vs gcc. Who's right?
template<typename TF>
void call(TF&& f)
{
f(1);
}
struct Example
{
void foo(int){ }
void bar()
{
call([this](auto x){ foo(x); });
}
};
int main()
{
Example{}.bar();
return 0;
}
- With
bar()
=call([this](auto x){ foo(x); });
- clang++ 3.6+ compiles.
- g++ 5.2+ does not compile.
error: cannot call member function 'void Example::foo(int)' without object call([this](auto x){ foo(x); });`
- With
bar()
=call([this](auto x){ this->foo(x); });
- clang++ 3.6+ compiles.
- g++ 5.2+ compiles.
- With
bar()
=call([this](int x){ foo(x); });
- clang++ 3.6+ compiles.
- g++ 5.2+ compiles.
- With
bar()
=[this](auto x){ foo(x); }(1);
- clang++ 3.6+ compiles.
- g++ 5.2+ compiles.
Why is the this->
necessary only in the case of a generic lambda?
Why is the this->
not necessary if the lambda isn't passed to call
?
Who is being non standard-compliant?
This is a gcc bug. From [expr.prim.lambda]:
Since in your example you capture
this
, the name lookup should include class members ofExample
, which should therefore findExample::foo
. The lookup performed is identical to what would happen iffoo(x)
appeared in the context of the lambda-expression itself, that is if the code looked like:At least this bug has a very simple workaround as indicated in the question: just do
this->foo(x);
.