为什么在使用 typeid 运算符时需要#include <typeinfo>?

Why do I need to #include <typeinfo> when using the typeid operator?

保存(动态)类型特定信息的typeid represents a C++ RTTI operator being also a C++ keyword. It returns a std::type_infoobject。

据我从各种渠道了解,使用typeid时必须包含<typeinfo>,否则程序为ill-formed。事实上,如果我不包含 before-mentioned header,我的 gcc5.2 编译器甚至不会编译程序。我不明白为什么使用 C++ 关键字 时必须包含 header。我理解每当我们在 header 中使用某些 object declared/defined 时强制使用 header,但 typeid 不是 class 类型。那么强制执行 header <typeinfo> 背后的原因是什么?

下一段:

The typeid expression is lvalue expression which refers to an object with static storage duration, of the polymorphic type const std::type_info or of some type derived from it.

因为是左值表达式,所以用了reference initialization to declare an initializer of std::type_info. <typeinfo> contains the definition for that object.

typeid 不是唯一需要 header

new 在某些情况下也需要 header <new>

Note: the implicit declarations do not introduce the names std, std::bad_alloc, and std::size_t, or any other names that the library uses to declare these names. Thus, a new-expression, delete-expression or function call that refers to one of these functions without including the header is well-formed. However, referring to std, std::bad_alloc, and std::size_t is ill-formed unless the name has been declared by including the appropriate header. —end note

See abhay's answer on new keyword

另一个运算符 sizeof which returns std::size_t (它实际上不需要包含 header,但我的意思是它使用了一个别名,它也是在 header)

中定义

C++ §5.3.3

The result of sizeof and sizeof... is a constant of type std::size_t. [Note: std::size_t is defined in the standard header <cstddef>(18.2).— end note]

typeid 使用在 <typeinfo> header

中声明的 类

Header <typeinfo> 剧情简介

namespace std {
class type_info;
class bad_cast;
class bad_typeid;
}

See section 18.7 on iso cpp paper

IMO,它的 C++ 标准设计技术,使编译器保持整洁、干净和轻量级