Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a this pointer in a generic lambda capture

Tags:

c++

lambda

c++14

I have an issue in which Clang (3.6) and G++ (5.1) have a differing opinion:

#include <functional>

struct X
{
    X()
    {
        std::function<void (int)> f = [this](auto x){foo(x);};
    }

    void foo(int x){}
};

int main(){}

Clang accepts this, whereas G++ states:

error: cannot call member function ‘void X::foo(int)’ without object

Both compilers accept it if I call this->foo(x) directly instead, but I'd rather know who's right.

Note: both the "auto" in the lambda signature and the conversion to a std::function<> are required to trigger this case.

like image 444
Kaz Dragon Avatar asked Mar 01 '26 01:03

Kaz Dragon


1 Answers

Both compilers accept it if I call this->foo(x) directly instead, but I'd rather know who's right.

Considering it compiles in gcc 5.2, clang is the one correct in your specific case. It looks like it was just a bug in gcc 5.1. gcc 6.0 also compiles this fine.

Plus it makes intuitive sense, this should be implied.

like image 127
Blindy Avatar answered Mar 02 '26 16:03

Blindy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!