gpt4 book ai didi

c++ - 为什么 'typeid(x) == typeid(y)'评估为true,而 'x'和 'y'分别是类型T和T&的id表达式?

转载 作者:行者123 更新时间:2023-12-01 13:34:07 29 4
gpt4 key购买 nike

我正在阅读C++ 11草案标准,关于[expr.typeid]的部分提到了以下内容(强调我的意思):

[...]

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand (Clause 5).

When typeid is applied to a type-id, the result refers to a std::type_info object representing the type of the type-id. If the type of the type-id is a reference to a possibly cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified referenced type. If the type of the type-id is a class type or a reference to a class type, the class shall be completely-defined.



在同一部分的p5中,进一步给出了以下示例:
class D { /* ... */ };
D d1;
const D d2;

typeid(d1) == typeid(d2); // yields true
typeid(D) == typeid(const D); // yields true
typeid(D) == typeid(d2); // yields true
typeid(D) == typeid(const D&); // yields true -- (1)

给定以下代码示例:
int main()
{
int foo = 42;
int &bar = foo;
bool comp1 = (typeid(int) == typeid(int&)); // Yields true, same as (1) -- (2)
bool comp2 = (typeid(foo) == typeid(bar)); // Yields true, Why? -- (3)
}

我的理解是 [expr.typeid] p4 只讨论typeid(type-id)形式,而 bar中的 typeid(bar)是id表达式,而不是type-id。为什么上面的(3)评估为 true?标准中的哪个文本涵盖了这一点?我错过了什么?

最佳答案

答案是 [expr]

5 If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.



因此,当我们进入 [expr.typeid]

3 When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) conversions are not applied to the expression. If the type of the expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand (Clause [expr]).



typeid检查它时,所讨论的id表达式已经是引用类型。

关于c++ - 为什么 'typeid(x) == typeid(y)'评估为true,而 'x'和 'y'分别是类型T和T&的id表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62134074/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com