Last Updated on 2021-10-22 by Clay
在 C++ 中,我們可以很清楚自己所定義的變數的資料型態;然而,對於第三方函式庫或是一些外部文件所傳入的參數,有時恐怕不是那麼有把握。
這時候,我們可以透過標準函式庫 typeinfo 中的 typeid() 來確認變數的資料型態。
typeid 使用方法
typeid() 返回的結果為 type_info 型態,也可以使用 .name() 函式返回系統型態名稱(是 C-style 字串,可以透過 printf("%s") 印出)。
而 .name() 返回的結果可以參考下表:
| 資料型態 | name() 返回名稱參考 |
|---|---|
| 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 |
除了這些基本的資料型態外,還有許多不同的類型,比方說 STL、自訂義類別之類的。大家可以稍微試試。
以下是段範例程式碼:
#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