Rei Rei - 3 months ago 11
C++ Question

Passing lambda to an object and modify that object from inside the lambda

I have code that looks like this:


struct LambdaContainer{
std::function<void(void)> f;
float x = 10;
}

struct MyClass{
LambdaContainer c;

}
void someFunction(){
MyClass ins;
LambdaContainer cont;
cont.f = [&cont](){
// I want to modify 'x' of LambdaContainer that is inside MyClass

cont.x = 10; // won't work because cont will be copy constructed
// and this cont might not exist anymore
};
ins.c = cont;
aVectorSomewhere.push_back(ins);
}


Is there any way I can capture the LambdaContainer 'cont' in such a way that it's referring to wherever the lambda is called from? (I'm not using pointer, by the way)


Thank you for such great answers :) I think I can get it to work now

Answer

Instead of capturing cont, pass it to the stored lambda:

class LambdaContainer
{ 
private:
    std::function<void(LambdaContainer&)> f;

public:
    float x = 10;

    void call_f()
    {
        f(*this);
    }
};

void someFunction()
{
    MyClass ins;
    LambdaContainer cont;
    cont.f = [](LambdaContainer& self)
    {    
        self.x = 10;
    };

    ins.c = cont;
    aVectorSomewhere.push_back(ins);
}

When you want to invoke the lambda, simply execute LambdaContainer::call_f from an existing instance or add a way to call call_f from MyClass depending on your design.

Comments