#include <iostream>
int main(){
auto lambda = [] {
return 7;
};
std::cout << lambda() << '\n';
}
This program compiles and prints 7.
The return type of the lambda is deduced to the integer type based on the return value of 7.
Why isn't this possible with ordinary functions?
#include <iostream>
auto function(){
return 42;
}
int main(){
std::cout << function() << '\n';
}
error: ‘function’ function uses ‘auto’ type specifier without trailing return type
C++14 has this feature. You can test it with new versions of GCC or clang by setting the
-std=c++1y
flag.Live example
In addition to that, in C++14 you can also use
decltype(auto)
(which mirrorsdecltype(auto)
as that of variables) for your function to deduce its return value usingdecltype
semantics.An example would be that for forwarding functions, for which
decltype(auto)
is particularly useful:With the use of
decltype(auto)
, you mimic the actual return type offunc
when called with the specified arguments. There's no more duplication of code in the trailing return type which is very frustrating and error-prone in C++11.