Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

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

The typeid represents a C++ RTTI operator being also a C++ keyword. It returns a std::type_info object that holds (dynamic) type specific information.

From what I understood from various sources, one MUST include <typeinfo> when using typeid, otherwise the program is ill-formed. In fact, my gcc5.2 compiler doesn't even compile the program if I don't include the before-mentioned header. I don't understand why is a header inclusion mandated for the usage of a C++ keyword. I understand mandating a header for whenever we use some object declared/defined in that header, but typeid is not of a class type. So what is the reason behind this enforcement of including the header <typeinfo>?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The next paragraph:

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.

Because it is an lvalue expression, which uses reference initialization to declare an initializer of std::type_info. <typeinfo> contains the definition for that object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...