问题描述
我认为(认为)我了解auto
.关于decltype
也是一样.但是,在C ++ 14中,可以将诸如decltype(auto)
之类的双合成对象作为函数的返回类型.请考虑以下内容:
I think (thought) I understand auto
. Same about decltype
. However, in C++14, one can have some diabolic thing like decltype(auto)
as the return type of a function. Consider the following:
decltype(auto) foo()
{
int m = 1;
return m;
}
返回类型为int
,一切都有道理.
The return type is int
, everything makes sense.
但是,
decltype(auto) foo()
{
int m = 1;
return (m);
}
返回int&
(即对int
的引用).
我绝对不知道为什么会这样,为什么这些括号根本没有任何区别!?希望有人能对此有所启发.
I have absolutely NO IDEA why this happens, why do these parentheses make any difference at all!? Hope someone can shed some light on this.
PS:我还用C++
进行了标记,因为检查C++
标签的人数比C++14
多.
PS: I've also tagged with C++
as there are many more people that check the C++
tag than C++14
.
推荐答案
7.1.6.2 [dcl.type.simple]
7.1.6.2 [dcl.type.simple]
- 对于表达式e,由decltype(e)表示的类型定义如下:
—如果e是未括号化的id表达式或未括号化的类成员访问权限(5.2.5),则decltype(e)是e命名的实体的类型.如果没有这样的实体,或者如果e命名了一组重载函数,则程序的格式不正确;
—否则,如果e是一个x值,则decltype(e)是T&& ;,其中T是e;的类型;
—否则,如果e为左值,则decltype(e)为T& ;,其中T为e的类型;
—否则,decltype(e)是e的类型.
- For an expression e, the type denoted by decltype(e) is defined as follows:
— if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;
— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
— otherwise, decltype(e) is the type of e.
在您的示例中,您有return (m)
,因此e
是(m)
.这不是非括号化的id表达式或类成员访问,因此我们转到第二个项目符号.它不是xvalue,因此我们转到第三个项目符号.它是一个左值,因此类型为T&
,其中T
为int
.
In your example you have return (m)
so e
is (m)
. That is not an unparenthesized id-expression or class member access, so we go to the second bullet. It is not an xvalue so we go to the third bullet. It is an lvalue, so the type is T&
where T
is int
.
这篇关于为什么decltype(auto)在这里返回引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!