【问题标题】:decltype((x)) with double brackets what does it mean? [duplicate]decltype((x)) 带双括号是什么意思? [复制]
【发布时间】:2019-06-11 10:43:18
【问题描述】:

非常简单的问题,我无法搜索到答案。

例如:

int a = 0;
int& b = x;
int&& c = 1;

decltype((a)) x; // what is the type of x?
decltype((b)) y; // what is the type of y?
decltype((c)) z; // what is the type of z?

也许我应该将 x、y 和 z 分配给某个值以获得不同的结果,我不确定。

编辑: 根据下面的双括号将示例int 转换为参考: https://github.com/AnthonyCalandra/modern-cpp-features#decltype

int a = 1; // `a` is declared as type `int`
int&& f = 1; // `f` is declared as type `int&&`
decltype(f) g = 1; // `decltype(f) is `int&&`
decltype((a)) h = g; // `decltype((a))` is int&

【问题讨论】:

  • (a),(b),(c) 是左值表达式。和 decltype(a = 1) 一样

标签: c++ c++11 reference rvalue-reference decltype


【解决方案1】:

它们都是int&类型。

添加像(a) 这样的括号使它们成为表达式(而不是entity),它们都是左值(作为命名变量);然后decltype 屈服于T&,即这里的int&

...

4) 如果参数是T 类型的任何其他表达式,并且

...

b) 如果表达式的值类别是左值,则 decltype 产生 T&;

...

您可以使用此LIVE DEMO(来自编译错误消息)检查实际类型。

【讨论】:

    【解决方案2】:

    根据C++ Primer

    当我们将decltype 应用于不带任何括号的变量时,我们得到 该变量的类型。如果我们将变量的名称包装在一个或 更多组括号,编译器会将操作数评估为 表达。变量是可以是左侧的表达式 的一项任务。结果,decltype 在这样的表达式上产生 参考:

    // decltype of a parenthesized variable is always a reference
    decltype((i)) d; // error: d is int& and must be initialized
    decltype(i) e;   // ok: e is an (uninitialized) int
    

    【讨论】:

      【解决方案3】:

      请注意,如果一个对象的名称被括号括起来,它被视为 一个普通的左值表达式,因此 decltype(x) 和 decltype((x)) 是 通常是不同的类型。

      https://en.cppreference.com/w/cpp/language/decltype

      据我了解,(x) 是一个空表达式,它返回对x 的引用。因此

      • decltype(x)int
      • declytpe((x))int&

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-15
        • 2017-02-01
        • 2014-10-24
        • 2014-10-03
        • 2011-01-17
        相关资源
        最近更新 更多