该程序编译并打印 7.lambda 的返回类型根据返回值 7 推导出整数类型.
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() << ' '; }错误:‘function’函数使用‘auto’类型说明符,没有尾随返回类型
推荐答案C++14 具有此功能.您可以通过设置 -std=c++1y 标志,使用新版本的 GCC 或 clang 对其进行测试.
C++14 has this feature. You can test it with new versions of GCC or clang by setting the -std=c++1y flag.
实例
除此之外,在 C++14 中,您还可以为您的函数使用 decltype(auto)(将 decltype(auto) 镜像为变量)使用 decltype 语义推断其返回值.
In addition to that, in C++14 you can also use decltype(auto) (which mirrors decltype(auto) as that of variables) for your function to deduce its return value using decltype semantics.
一个例子是转发函数,其中 decltype(auto) 特别有用:
An example would be that for forwarding functions, for which decltype(auto) is particularly useful:
template<typename function_type, typename... arg_types> decltype(auto) do_nothing_but_forward(function_type func, arg_types&&... args) { return func(std::forward<arg_types>(args)...); }通过使用 decltype(auto),您可以在使用指定参数调用时模拟 func 的实际返回类型.尾随返回类型中不再有重复的代码,这在 C++11 中非常令人沮丧且容易出错.
With the use of decltype(auto), you mimic the actual return type of func 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.
更多推荐
可以通过返回值推导出 lambda 的返回类型,那么为什么函数不能呢?
发布评论