65

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::.

BartoszKP
  • 33,416
  • 13
  • 100
  • 127
HighCommander4
  • 47,099
  • 23
  • 115
  • 186

1 Answers1

58

I agree, it should compile just fine. For the fix (if you didn't know already), just 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; };
};
Mikael Persson
  • 17,628
  • 6
  • 35
  • 50
  • 39
    Could they have made lambda's more ugly? Don't answer that. At least we've got them. – wheaties Feb 09 '11 at 03:35
  • 37
    @wheaties I am disappointed they couldn't work in `<>` somehow. Just to go for the full set of brackets... – KitsuneYMG Feb 09 '11 at 03:54
  • 23
    @KitsuneYMG: There is an example at http://msdn.microsoft.com/en-us/library/dd293599.aspx: auto g = [](int x) -> function { return [=](int y) { return x + y; }; }; – TonyK Feb 09 '11 at 12:10