Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't a const mutable lambda with an auto& parameter be invoked?

#include <type_traits>

int main()
{
    auto f1 = [](auto&) mutable {};
    static_assert(std::is_invocable_v<decltype(f1), int&>); // ok

    auto const f2 = [](auto&) {};
    static_assert(std::is_invocable_v<decltype(f2), int&>); // ok

    auto const f3 = [](auto&) mutable {};
    static_assert(std::is_invocable_v<decltype(f3), int&>); // failed
}

See demo

Why can’t a const mutable lambda take a reference argument?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You get an error for this for the very same reason:

struct foo {
    void operator()(){}
};

int main() {
    const foo f;
    f();
}

The error is:

<source>:7:5: error: no matching function for call to object of type 'const foo'
    f();
    ^
<source>:2:10: note: candidate function not viable: 'this' argument has type 'const foo', but method is not marked const
    void operator()(){}
         ^

Because you cannot call a non-const method on a const instance. Lambdas got the default constness right, so without mutable the operator() is const. With mutable the operator() is a non-const method that you cannot call on a const f3;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading