How to reset lambdas?


#1

Let’s say that I have a class with the following lambda as member

class MyClass {
public:
    MyClass();

    void setup();
    void build();
    void clear();
    //...

    std::function<glm::vec3(float, int, int)> addOffset;
};

I can add lambda to my class doing something like:

instanceOfMyClass.addOffset = [](float angle, int segmentIndex, int pointIndex ){
            auto x = sin(angle*3.0) * 0.1;
            auto y = sin(segmentIndex*0.9) *0.8;
            auto z = cos(pointIndex*1.3) * 2.0;
            return glm::vec3(x,y,z);
}

In the implementation file, at the method build, i check if the lambda was set, and if it was set I call it:

void myClass::build(){
     // ...
    if (addOffset) {
        offset = addOffset(phi, i, j);
     }
}

Now, I would like to add a method called resetOffset, that will reset my lambda to the initial state, in a way that the check on if (addOffset) in the build method will return false. How am I supposed to do it? should i set it to a nullptr?


#2

Looks nullptr do the job.
boost::function has clear() method but std doesn’t.


#3

thanks, setting the lambda to nullptr works. It did not sound that clean, but it works :wink: