为什么decltype定义一个变量作为参考? [英] Why is decltype defining a variable as a reference?

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

问题描述

我正在研究 auto decltype 类型说明符之间的差异,我在另一个问题中看到,当我请使用 decltype ,如下所示:

  const int ci = 0,& cj = ci; 
decltype(ci)x = 0;
decltype(cj)y = x;

decltype(cj) cj 指向(即 const int )的对象的类型,但会给出类型 cj 本身。因此 y 将会是 const int&



这是否发生?它可能会影响我的代码在某处?是否与 decltype() decltype(())

解决方案

decltype 的规则相当简单(尤其是与许多其他规则相比) ..)。对于表达式 e decltype(e)是(from [dcl.type.simple],释义) / p>


  • 如果 e 是未加括号的 id-expression 那么 e 的类型。正确的类型 e 。我们不会丢弃 cv - 数据或引用或任何内容。 decltype(ci) const int ,因为这是 ci 。同样, decltype(cj) const int&

  • code> e 是xvalue,则 T&&& 其中 T e 的类型。

  • 如果 e 是一个左值, T& 其中 T e 的类型。 / li>
  • 否则, e 的类型。



我们按顺序通过这些要点。括号有区别的是当我们 decltype((ci)) - (ci) id-expression ,因此我们不能简单地使用 ci 的类型。相反,它只是一个左值 - 所以我们接受表达式的类型( const int )并添加一个引用。因此, decltype((ci)) const int& decltype((cj))仍然是 const int&


I was studying about the differences between auto and decltype type specifier and I saw in another question that when I use decltype with a reference, like this:

const int ci = 0, &cj = ci;
decltype(ci) x = 0;
decltype(cj) y = x; 

decltype(cj) will not give me the type of the object that cj refers to (that is, const int) but will give me the type of cj itself. So y will be const int&.

Why does this happen? And it could affect my code in someway? Is it related to the difference between decltype() and decltype(())?

解决方案

The rules of decltype are fairly straightforward (especially when compared to lots of other rules in C++...). For an expression e, decltype(e) is (from [dcl.type.simple], paraphrasing):

  • if e is an unparenthesized id-expression, then the type of e. Exactly the type of e. We're not dropping cv-qualifiers or references or anything. decltype(ci) is const int because that is the type of ci. Likewise, decltype(cj) is const int&.
  • If e is an xvalue, then T&& where T is the type of e.
  • If e is an lvalue, then T& where T is the type of e.
  • Else, the type of e.

We go in order through those bullet points. Where the parentheses makes a difference is when we do decltype((ci)) - (ci) is not an unparenthesized id-expression anymore, so we don't simply take the type of ci. Instead, it's just an lvalue - so we take the type of the expression (const int) and add a reference to it. Hence, decltype((ci)) is const int&. decltype((cj)) is still const int&.

这篇关于为什么decltype定义一个变量作为参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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