C++14 Lambda - Conditionally Capture by Reference or Value

c++, c++14, lambda

Solution

Lambda capture type cannot be controlled by template-dependent names.

However, you could achieve the desired effect by delegating creating the inner lambda to an overloaded function:

template<class T>
auto make_monad(T&& arg) {
    return [captive = std::forward<T>(arg)](auto&& a) {
        std::cout << __PRETTY_FUNCTION__ << " " << a << '\n';
        return 1;
    };
}

template<class T>
auto make_monad(std::reference_wrapper<T> arg) {
    return [&captive = static_cast<T&>(arg)](auto&& a) {
        std::cout << __PRETTY_FUNCTION__ << " " << a << '\n';
        return 1;
    };
}

int main() {
    auto monad = [](auto&& captive) {
        return make_monad(std::forward<decltype(captive)>(captive));
    };

    int n = 1;
    monad(1)(1);
    monad(n)(2);
    monad(std::ref(n))(3);
}

Outputs:

make_monad(T&&)::<lambda(auto:1&&)> [with auto:1 = int; T = int] 1
make_monad(T&&)::<lambda(auto:1&&)> [with auto:1 = int; T = int&] 2
make_monad(std::reference_wrapper<_Tp>)::<lambda(auto:2&&)> [with auto:2 = int; T = int] 3

I don't want to capture reference_wrapper by reference, I want to capture the reference it holds by reference. Reference wrapper does it's best to be a like a reference, but since the call operator (aka, "." operator) cannot be overloaded, it fails pretty miserably at the end of the day.

In this case you do not need to change the capture type for `std::reference_wrapper<T>`. Instead, you may like to capture it by value like any other type of argument and at the usage site unwrap the argument first:

template<class T> T& unwrap(T& t) { return t; }
template<class T> T& unwrap(std::reference_wrapper<T> t) { return t; }

auto monad = [](auto && captive) {
    return [captive](auto && a) {            // <--- Capture by value.
        auto& captive_ref = unwrap(captive); // <--- Unwrap before usage.
        return 1;
    };
};

Problem

Is it possible to conditionally choose the capture method of a lambda based on compile time information? For example... ``` auto monad = [](auto && captive) { return [(?)captive = std::forward<decltype(captive)>(captive)](auto && a) { return 1; }; }; ``` I want capture by reference if `decltype(captive)` is a `std::reference_wrapper`, and everything else captured by value.

Original source