Last Updated on 2021-10-22 by Clay
In C++, we always can be clear about the data type of the variables we declared; however, sometimes we passed in some parameters from third-party libraries, so we are not so sure which data type it is.
At this time, we can confirm the data type of the variable through typeid()
in the standard library typeinfo
.
The usage of typeid()
The typeid()
function will return a type_info
type, and you can also use .name()
to return the system type name that is a C-style string, you can use printf("%s")
to print it out.
The .name()
results can refer the table:
Data Type | name() return tag |
---|---|
bool | b |
char | c |
signed char | a |
unsigned char | h |
signed short int | s |
unsigned short int | t |
signed int | i |
unsigned int | j |
signed long int | l |
unsigned long int | m |
signed long long int | x |
unsigned long long int | y |
float | f |
double | d |
long double | e |
In addition to these basic data types, there are many different types, such as STL and custom class. You can try it a little bit.
The following is a sample code:
#include <iostream>
#include <typeinfo>
int main() {
// Init
int a = 10;
long int b = 100000;
int c = 10;
// typeid()
const std::type_info &ai = typeid(a);
const std::type_info &bi = typeid(b);
const std::type_info &ci = typeid(c);
// Print
printf("a: %p | %s\n", &ai, ai.name());
printf("b: %p | %s\n", &bi, bi.name());
printf("c: %p | %s\n\n", &ci, ci.name());
// Judge a == b
printf("&ai == &bi: %d\n", &ai == &bi); // Not guaranteed
printf("hash_code : %d\n\n", ai.hash_code() == bi.hash_code()); // Guaranteed
// Judge a == c
printf("&ai == &ci: %d\n", &ai == &ci); // Not guaranteed
printf("hash_code : %d\n", ai.hash_code() == ci.hash_code()); // Guaranteed
return 0;
}
Output:
a: 0x7fff8027dbe8 | i
b: 0x7fff8027dc88 | l
c: 0x7fff8027dbe8 | i
&ai == &bi: 0
hash_code : 0
&ai == &ci: 1
hash_code : 1
References
- https://en.cppreference.com/w/cpp/language/typeid
- https://stackoverflow.com/questions/36219532/serializing-stdtype-index