13.48 <typeinfo>The <typeinfo> header declares the type_info class (for the typeid operator) and two exception classes related to type information and casting.
The dynamic_cast<> operator throws bad_cast when the cast of a reference fails. See dynamic_cast in Chapter 3 for more information. See Alsodynamic_cast operator
The typeid operator throws bad_typeid when it is applied to an expression of the form *p, in which p is a null pointer. See typeid in Chapter 3 for more information. See Alsotypeid operator
The typeid operator (described in Chapter 3) returns a static type_info object. The type information includes the type's name and a collation order, both of which are implementation-defined. An implementation might derive classes from type_info to provide additional information. Note that the copy constructor and assignment operators are inaccessible, so you must store pointers if you want to use a standard container. Example 13-38 shows how to store type_info pointers in a set, where the order is determined by the before member function. ExampleExample 13-38. Storing type information#include <algorithm> #include <functional> #include <iostream> #include <ostream> #include <set> #include <typeinfo> typedef bool (*type_info_compare) (const std::type_info*, const std::type_info*); typedef std::set<const std::type_info*, type_info_compare> typeset; // Return true if *a comes before *b (comparison function to store type_info // pointers in an associative container). bool type_info_less(const std::type_info* a, const std::type_info* b) { return a->before(*b); } // Print a type_info name on a line. void print(const std::type_info* x) { std::cout << x->name( ) << '\n'; } void demo( ) { // Construct and initialize the set. typeset types(&type_info_less); types.insert(&typeid(int)); types.insert(&typeid(char)); types.insert(&typeid(std::type_info)); types.insert(&typeid(std::bad_alloc)); types.insert(&typeid(std::exception)); . . . // Print the types in the set. std::for_each(types.begin( ), types.end( ), print); } The members of type_info are:
See Also |