"decltype"是否为我提供了对象的静态类型或其运行时类型?
Does `decltype` give me an object's static type, or its runtime type?
[C++11: 7.1.6.2/4]:
由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
的类型
decltype
说明符的操作数是未赋值的操作数(第5条(。
第二种、第三种和第四种情况清楚地提到了表达的类型,其中不包括任何多态性因素。
然而,我不完全确定">实体"在这里是什么意思,第一个情况似乎是命名表达式e
引用的对象。"实体的类型"是指它的运行时类型,还是静态类型,我对此并不清楚。
由于第一种情况的限制,实际上不可能遇到这个问题。
考虑:
struct A {};
struct B : A {};
int main()
{
A* x = new B();
// What is `decltype(*x)`?
}
CCD_ 21的使用使我们陷入了第三种情况。
作为参考?
struct A {};
struct B : A {};
int main()
{
A& x = *(new B());
// What is `decltype(x)`?
}
x
是一个类型为A&
的引用,它是该"实体"的类型结果。
使用第一种情况的唯一方法是直接命名对象,而我们不能以隐藏运行时类型的方式这样做:
struct A {};
struct B : A { void foo() {} };
int main()
{
A x = B(); // well, you've sliced it now, innit?
decltype(x) y;
y.foo(); // error: ‘struct A’ has no member named ‘foo’
}
这就是为什么根据这些答案,总是使用对象的静态类型
您不必查看各个点:结果decltype
是编译器已知的类型很大程度上排除了任何动态类型。还有你说的最后一句话引号再明确不过了:没有对说明符求值,这也排除了任何动态打字。
这基本上是一个"实体"在这里意味着什么的问题(可能的含义在第3条中定义(。考虑
struct A {
int a;
};
int main() {
A a = {};
const A b = {};
const A *aptr = (rand() % 42) ? &a : &b;
decltype(aptr->a) x = 0;
decltype((aptr->a)) y = 0;
}
x
的类型是const int
还是int
?如果将实体表示为"成员",则它是int
,因为成员A::a
的类型为int
。如果采用实体类型"object",则类型为const int
或int
,具体取决于rand()
的结果。对象、它们的存在和属性(通常包括它们的类型(是一个运行时问题。
我要说的是,这并不是真正的模棱两可。因为每个人都知道这是什么意思,因为标准使用了短语"由e命名",而不是"由e引用"或"由e表示",这表明它只是名称查找结果。
注意,y
的类型是始终const int&
,因为表达式aptr->a
的类型是const int
,并且它是左值。
- 调用具有未标识类型的类的方法
- C++ 中模板化类型的类层次结构
- 在C++中使用非静态类函数的函数
- 根据模板类型选择类模板的成员类型?
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- C++从抽象类型定义类成员
- 实例化具有不完整类型的类模板格式不正确(如果该类型是在之后定义的)
- 重载模板<类型名...>类的函数模板
- 如果静态成员未初始化并且成员类型是类本身,该怎么办?
- 获取静态类功能的类类型
- 静态类模板成员:将"sizeof"应用于不完整类型无效
- 如何创建一个编译时静态类类型,该类型初始化具有特定值的成员容器
- C++ 具有静态成员的模板类 - 对于类的所有类型的类都相同
- 类自己的类型的静态类成员
- 我们如何能够在与类具有相同数据类型的类中声明静态成员
- 另一个类中使用的非静态类<未解析的重载函数类型>
- 在类中声明的静态变量,其类型与类的类型相同
- 为什么静态类类型函数返回零
- double类型静态类成员的常量表达式初始化项
- 初始化vector类型的静态类成员