lambda的返回类型可以通过返回值推导出来,那么为什么函数不能呢?

编程入门 行业动态 更新时间:2024-10-21 07:42:47
本文介绍了lambda的返回类型可以通过返回值推导出来,那么为什么函数不能呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include <iostream> int main(){ auto lambda = [] { return 7; }; std::cout << lambda() << '\n'; }

此程式编译并列印7. 基于返回值7,lambda的返回类型被推导为整数类型。

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'; }

错误:'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) code>,当使用指定的参数调用时,模拟 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的返回类型可以通过返回值推导出来,那么为什么函数不能呢?

本文发布于:2023-10-31 06:09:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545243.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以通过   函数   返回值   类型   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!