Steve Emmerson Steve Emmerson - 26 days ago 9
C++ Question

How to have local anonymous C++ function object use argument from containing method?

What's the correct way to have an anonymous local function object access an argument of the containing method? I.e., what's the correct way to do the following:

void A::foo(B& b)
{
struct {
void operator()() {b.bar();}
} func;
func();
}


NB: This example is contrived for simplicity: the actual use-case involves applying an anonymous local function object to each element in a container to have the element act on the argument of the containing method.

Answer

You need to pass the reference/pointer of the worked-on object to the anonymous one. But since it's anonymous, you cannot declare its constructor. If you named it, you'd be able to say:

void A::foo(B& b)
{
    struct Foo{
        B& b;
        Foo(B& b) : b(b) {}
        void operator()() {b.bar();}
    } func{b};
    func();
}

That being said, in C++11 - as you tagged this question - you could use a lambda expression:

void A::foo(B& b)
{
    auto func = [&]{ b.bar(); };
    func();
}
Comments