How to make const some members of a mutable lambda capture list?

Viewed 181

mutable lambda can change the values of the members of its capture list (that were captured by value). Is there any way to make some members of the capture list remain const in the mutable lambda?

E.g. I want to change i but have const j in the body of lambda in the following code sample:

#include <iostream>

int main()
{
    int i = 42;
    int j = 108;
    auto lambda = [i, j]() mutable
    {
        i = 15;
        std::cout << "i = " << i << std::endl;
        std::cout << "j = " << j << std::endl;
    };

    lambda();
}
1 Answers

Since simple captures have the exact, cv-qualified type of the thing they capture, you can make the outer variable const and thus get a const capture:

#include <iostream>

int main()
{
    const int i = 42;
//  ^^^^^

    int j = 108;
    auto lambda = [i, j]() mutable
    {
        i = 15;
        std::cout << "i = " << i << std::endl;
        std::cout << "j = " << j << std::endl;
    };

    lambda();
}

Of course if you need to modify the outer variable at some point, you need to make a copy of it first -- or refactor your code in some way to make this a bit tidier.

Related