There is no corresponding function std :: forward with lambdas

Consider the following code inspired by Barry's answer to this question :

// Include
#include <tuple>
#include <utility>
#include <iostream>
#include <type_traits>

// Generic overload rank
template <std::size_t N> 
struct overload_rank 
: overload_rank<N - 1> 
{
};

// Default overload rank
template <> 
struct overload_rank<0> 
{
};

// Prepend argument to function
template <std::size_t N, class F>
auto prepend_overload_rank(F&& f) {
    using rank = overload_rank<N>;
    return [f = std::forward<F>(f)](rank, auto&&... args) -> decltype(auto) {
        return std::forward<F>(f)(std::forward<decltype(args)>(args)...); // here
    };
}

// Main
int main(int argc, char* argv[])
{
    auto f = [](int i){return i;};
    prepend_overload_rank<5>(f)(overload_rank<5>(), 1);
    return 0;
}

It does not compile due to the marked line here, and I do not understand why:

With g++:
error: no matching function for call to 'forward<main(int, char**)::<lambda(int)>&>(const main(int, char**)::<lambda(int)>&)'
With clang:
error: no matching function for call to 'forward'

Replacement

return std::forward<F>(f)(std::forward<decltype(args)>(args)...); 

by

return f(std::forward<decltype(args)>(args)...); 

obviously makes it work, but then again, I donโ€™t understand why, and my goal is to achieve the perfect function transfer.

+4
source share
1 answer

-, , , , const, mutable .
, GCC, clang:

#include <type_traits>

int main(int argc, char* argv[]) {
    int i = 0;
    [j = i](){ static_assert(std::is_same<decltype(j), const int>::value, "!"); }();
}

, :

return [f = std::forward<F>(f)](auto&&... args) -> decltype(auto) {
    return std::forward<decltype(f)>(f)(std::forward<decltype(args)>(args)...); // here
};

mutable, f . , f -, f decltype(f) .
mutable . :

#include <type_traits>
#include<utility>

struct S {};

template<typename T>
void f(T &&t) {
    [t = std::forward<T>(t)]()mutable{ static_assert(std::is_same<decltype(t), S>::value, "!"); }();
    // the following doesn't compile for T is S& that isn't the type of t within the lambda
    //[t = std::forward<T>(t)]()mutable{ static_assert(std::is_same<decltype(t), T>::value, "!"); }();
}

int main() {
    S s;
    f(s);
}

, , , .
, const, mutable, f const ( , f main mutable).

( ):

return [f = std::forward<F>(f)](auto&&... args) mutable -> decltype(auto) {
    return std::forward<F>(f)(std::forward<decltype(args)>(args)...); // here
};

, , const, - .
, , mutable.


.
- GCC. decltype(f) . . , , .

+2

Source: https://habr.com/ru/post/1668823/


All Articles