C++14 supports generic lambdas. However, the following code is rejected by clang 3.4.
#include <utility> void f(int); void f(int&); int main() { [](auto&& v) { f(std::forward<auto>(v)); }(8); // error }
How to perfectly forward auto&&
in a generic lambda?
What is Perfect Forwarding. Perfect forwarding allows a template function that accepts a set of arguments to forward these arguments to another function whilst retaining the lvalue or rvalue nature of the original function arguments.
The std::forward function as the std::move function aims at implementing move semantics in C++. The function takes a forwarding reference. According to the T template parameter, std::forward identifies whether an lvalue or an rvalue reference has been passed to it and returns a corresponding kind of reference.
C++ std::move does not move and std::forward does not forward. This article dives deep into a long list of rules on lvalues, rvalues, references, overloads and templates to be able to explain a few deceivingly simple lines of code using std::move and std::forward.
auto
is not a type so I’m not surprised this doesn’t work. But can’t you use decltype
?
[](auto&& v) { f(std::forward<decltype(v)>(v)); }(8);
Scott Meyers has more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With