Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...