Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return an object of type T by reference from a lambda without using trailing return type syntax?

Given the following code snippet:

struct T {};   std::function<T&(T&)> f = [](T& obj) -> T& { return obj; }; 

I was wondering if it is possible to infer the correct lambda return type (i.e. T&) without using trailing return type syntax.

Obviously, if I remove -> T& then a compile-time error will occur in that the deduced type would be T.

like image 963
FdeF Avatar asked Dec 05 '16 15:12

FdeF


2 Answers

In C++14, you can use [](T& obj) -> decltype(auto) { return obj; }. In that case, the return type of f is deduced from the declared type of obj (i. e. T& in this case).

like image 119
jsb Avatar answered Sep 20 '22 06:09

jsb


No, but in C++14 you could use auto& as the trailing-return-type. If it's typing you're worried about, and compiler upgrades don't worry you at all, then this mostly solves your problem.

like image 20
Lightness Races in Orbit Avatar answered Sep 23 '22 06:09

Lightness Races in Orbit