Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perfectly forward `auto&&` in a generic lambda?

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?

like image 506
xmllmx Avatar asked Jul 02 '14 15:07

xmllmx


People also ask

What is perfect forwarding?

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.

What std:: forward does?

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.

Does std copy forward?

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.


1 Answers

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.

like image 79
Konrad Rudolph Avatar answered Oct 04 '22 15:10

Konrad Rudolph