lambda的返回类型可以通过返回值推导出来,那么为什么函数不能呢? [英] A lambda's return type can be deduced by the return value, so why can't a function's?

查看:1349
本文介绍了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的返回类型可以通过返回值推导出来,那么为什么函数不能呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆