decltype行为背后的原理是什么? [英] What is the rationale behind decltype behavior?

查看:294
本文介绍了decltype行为背后的原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我在C ++ 11中所理解的,decltype(expression)用于推导给定表达式的完全相同的类型.但是,当将表达式放在括号中时,则推导类型是对该表达式类型的左值引用.例如:

As I understood in C++11 decltype(expression) is used to deduce the exact same type of the given expression. But when the expression is put into parentheses itself, then the deduces type is lvalue reference to the expression type. For example:

int x;
decltype(x) y = x;

等同于int y = x;,但是

int x;
decltype((x)) y = x;

等同于int& y = x;.

分别

 decltype(auto) f1()
 {
   int x = 0;
   return x; // decltype(x) is int, so f1 returns int
 }

但是

 decltype(auto) f2()
 {
   int x = 0;
   return (x); // decltype((x)) is int&, so f2 returns int&
 }

标准委员会选择此行为的理由是什么?

What is the rationale for this behavior to be chose by the standard committee?

后记:

现在,我观察到至少在 GCC 6.2 实现的情况下,括号中的表达式更复杂,例如decltype((x + x)),推导的类型为T,但不是T& .这更加令人困惑.我不知道这种行为是否正常.

Now I observed that at least in the case of GCC 6.2 implementation when the expression in the parentheses is more complex for example decltype((x + x)) the deduced type is T, but not T&. This is even more confusing. I don't know whether this behavior is standard.

推荐答案

他们想要一种获取标识符声明类型的方法.

They wanted a way to get the type of declaration of an identifier.

他们还希望获得一种表达式的类型,包括有关它是否为临时类型的信息.

They also wanted a way to get the type of an expression, including information about if it is a temporary or not.

decltype(x)给出标识符x的声明类型.如果传递的不是标识符的decltype东西,它将确定类型,然后为lvalues附加&,为xvalues附加&&,为prvalues附加任何内容.

decltype(x) gives the declared type of the identifier x. If you pass decltype something that is not an identifier, it determines the type, then appends & for lvalues, && for xvalues, and nothing for prvalues.

从概念上讲,您可以将其视为变量类型与表达式类型之间的差异.但这并不是标准描述的方式.

Conceptually you can think of it as the difference between the type of a variable and the type of an expression. But that is not quite how the standard describes it.

他们本可以使用两个不同的关键字来表示这两件事.他们没有.

They could have used two different keywords to mean these two things. They did not.

这篇关于decltype行为背后的原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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