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

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

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