typeid operator
From cppreference.com
Queries information of a type.
Used where the actual type of a virtual base class must be known.
Contents |
[edit] Syntax
typeid( type )
|
(1) | ||||||||
typeid( expression )
|
(2) | ||||||||
Header <typeinfo>
must be included before using typeid
operator.
Both versions return an object of type const std::type_info&.
[edit] Explanation
1) returns the type information about the type. The type will be definitely known compile time and no runtime overhead is caused.
2) expression is evaluated and type information corresponding to the resulting value is returned. If the expression is (or evaluates to) a polymorphic object, the actual type of the class is queried dynamically with some runtime overhead. Otherwise the actual type is definitely known compile time and no runtime overhead is incurred.
[edit] Keywords
[edit] Example
#include <iostream> #include <string> #include <typeinfo> int main(void) { int myint = 50; std::string mystr = "string"; double *mydoubleptr = new double; *mydoubleptr = 50.5321; std::cout << "myint has type: " << typeid(myint).name() << '\n'; std::cout << "mystr has type: " << typeid(mystr).name() << '\n'; std::cout << "mydoubleptr has type: " << typeid(mydoubleptr).name() << '\n'; delete mydoubleptr; }
Possible output:
myint has type: int mystr has type: std::basic_string<char, std::char_traits<char>, std::allocator<char> > mydoubleptr has type: double*