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

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

该程序编译并打印 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 的返回类型,那么为什么函数不能呢?

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

发布评论

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

>www.elefans.com

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