samedi 3 septembre 2016

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)

Aucun commentaire:

Enregistrer un commentaire