type_info class — Type information
class type_info { public: virtual ~type_info( ); bool operator==(const type_info& rhs) const; bool operator!=(const type_info& rhs) const; bool before(const type_info& rhs) const; const char* name( ) const; private: type_info(const type_info& rhs); type_info& operator=(const type_info& rhs); };
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.
Example 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:
bool
before
(const
type_info&
rhs)
const
Returns true
if this
type_info
object comes
before rhs
in the
implementation-defined order. The relative order of types can
vary between programs, even for the same types.
const
char*
name
( )
const
Returns the type's name as a null-terminated string, which might be a multibyte string. The contents of the name string are implementation-defined.
bool
operator==
(const type_info&
rhs) const
, bool
operator!=
(const type_info&
rhs) const
Compares type_info
objects, which are equal when the types they describe are the
same.