HighCommander4
HighCommander4

Reputation: 52739

lambdas require capturing 'this' to call static member function?

For the following code:

struct B
{
    void g()
    {
        []() { B::f(); }();
    }

    static void f();
};

g++ 4.6 gives the error:

test.cpp: In lambda function:
test.cpp:44:21: error: 'this' was not captured for this lambda function

(Interestingly, g++ 4.5 compiles the code fine).

Is this a bug in g++ 4.6, or is it really necessary to capture the 'this' parameter to be able to call a static member function? I don't see why it should be, I even qualified the call with B::.

Upvotes: 69

Views: 47821

Answers (1)

Mikael Persson
Mikael Persson

Reputation: 18562

I agree, it should compile just fine. For the fix (if you didn't know already), add the reference capture ([&]) and it will compile fine on GCC 4.6:

struct B
{
    void g()
    {
        [&]() { B::f(); }();
    }

    static void f() { std::cout << "Hello World" << std::endl; };
};

Upvotes: 60

Related Questions