Search code examples
c++lambdacapturemultiple-instancessingle-instance

Make a Single Capturing Lambda


This is obviously a toy example, but lets say I have a n functions like this:

void one(const int param) {
    const auto func = [=](){ return 13 == param; };
}

void two(const int param) {
    const auto func = [=](){ return 13 == param; };
}

And so on; they all have an identical capturing lambda. Is it possible to have 1 instance of the lambda which always captures the param of the function that it is in, rather than n instances? Maybe as a follow up question I should be asking, will the compiler already recognize the replication and simplify these to a single instance?


Solution

  • Unfortunately you will get multiple types with this solution. [expr.prim.lambda.closure]/1 states that

    The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.

    emphasis mine

    So each

    const auto func = [=](){ return 13 == param; };
    

    is its own expression so you get a new unique type, even though they are syntactically the same.

    What you could do is is factor the repetition out into a functor and then you would only have one class that is defined.

    class compare
    {
        int val;
    public:
        compare(int val) : val(val) {}
        bool operator() const { return val = 13; }
    };
    

    and then your functions would become

    void one(const int param) {
        const auto func = compare{param};
    }
    
    void two(const int param) {
        const auto func = compare{param};
    }