声明类型没有任何可变类型

decltype without any variable type

本文关键字:类型 任何可 声明      更新时间:2023-10-16

我对C 中的声明使用情况并不那么经验。但是以下是我最终出于项目目的到达的代码:

#include <iostream>
#include <inttypes.h>
#define SA(obj) ((obj)->u)
struct A
{
    A()
    {
    std::cout << "Called" << std::flush << std::endl;
    }
    uint32_t u;
};
int main()
{
    struct A a2;
    decltype(A().u) p;
    a2.u = 99;
    p = a2.u;
    if(a2.u != SA(&a2) )
    std::cout << "Not Same" << std::flush << std::endl;
    else
    std::cout << "Same" << std::flush << std::endl;
}

我可以看到A的构造函数仅称为以下语句的原因:

struct A a2;

同样关心的是,该构造中的构造是什么意思 - 它不会创建结构的临时实例 -

decltype(A().u) p;

如下声明给出了汇编错误:

decltype(A.u) p;
c++ -std=c++11 try5.cpp
try5.cpp: In function 'int main()':
try5.cpp:18:17: error: invalid type in declaration before ';' token
  decltype(A.u) p;

decltype括号内的表达式未评估。编译器仅分析了发现其类型,但从未转换为实际可执行代码。

A.u失败了分析阶段,因为您不能在类型名称之后使用.