decltype(auto)和decltype(returning expr)作为返回类型有什么区别? [英] What is difference between decltype(auto) and decltype(returning expr) as return type?

查看:140
本文介绍了decltype(auto)和decltype(returning expr)作为返回类型有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在两种情况下都使用expr而不带括号,则decltype(auto)decltype(returning expression)作为函数(模板)的返回类型有什么区别?

What is the difference between decltype(auto) and decltype(returning expression) as return type of a function (template) if expr used without parentheses in both cases?

auto f() -> decltype(auto) { return expr; } // 1
auto f() -> decltype(expr) { return expr; } // 2

f以上可以在任何上下文中定义/声明,并且可以是(成员)函数或(成员)函数模板,甚至可以是(通用)lambda. expr可以取决于任何模板参数.

Above f can be defined/declared in any context and can be either (member) function or (member) function template, or even (generic) lambda. expr can depend on any template parameters.

在第二个版本中,两个expr都是完全相同的表达式,没有多余的括号.

In second version both expr are exactly the same expression without extra parentheses.

在C ++ 14及更高版本中使用第一种或第二种形式,会有什么不同?

Which differences can one expect, using first or second form in C++14 and later?

如果到处都用括号怎么办?

What if parentheses used everywhere?

推荐答案

是的.第一个将基于函数主体中的return表达式检测返回类型.

Yes there is a difference. The first one will detect the return type based on the return expression in the body of the function.

第二个表达式不会同时将返回类型设置为decltype()内部表达式的类型,而是还会在其上应用 expression sfinae .这意味着,如果decltype中的表达式无效,则编译器将搜索另一个有效的重载.而第一个版本将是一个严重的错误.

The second one will not also set the return type to the type of the expression inside decltype(), but will also apply expression sfinae on it. That means that if the expression inside decltype is not valid, the compiler will search for another valid overload. Whereas the first version will be a hard error.

以这个例子为例:

template<typename T>
auto fun(T a) -> decltype(a.f()) { return a.f(); }

template<typename T>
auto fun(T a) -> decltype(a.g()) { return a.g(); }

struct SomeType {
    int g() { return 0; }
};

fun(SomeType{});

这将选择正确的过载.现在,如果我们将decltype(expr)替换为decltype(auto),编译器将无法选择正确的重载,因为函数签名中没有 会限制类型应该执行的操作

This select the correct overload. Now if we replace decltype(expr) by decltype(auto), the compiler will not be able to select the correct overload, as there's nothing in the function signature that constrains what the type is supposed to be able to do.

这篇关于decltype(auto)和decltype(returning expr)作为返回类型有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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