std::type_index
來自 cppreference.com
定義於標頭檔案 <typeindex> |
||
class type_index; |
(C++11 起) | |
type_index
類是 std::type_info 物件的包裝類,它可以用作關聯容器和無序關聯容器的索引。與 type_info
物件的關聯透過指標維護,因此 type_index
是 可複製構造的(CopyConstructible)和 可複製賦值的(CopyAssignable)。
目錄 |
[編輯] 成員函式
構造物件 (公共成員函式) | |
(解構函式) (隱式宣告) |
銷燬 type_index 物件(公開成員函式) |
operator= (隱式宣告) |
賦值 type_index 物件(公開成員函式) |
(在 C++20 中刪除)(C++20) |
比較底層 std::type_info 物件 (公共成員函式) |
返回雜湊碼 (公共成員函式) | |
返回型別(與底層 type_info 物件相關聯)的實現定義名稱。 associated with underlying type_info object (公共成員函式) |
[編輯] 輔助類
(C++11) |
為 std::type_index 提供雜湊支援 (類模板特化) |
[編輯] 示例
以下程式是型別-值高效對映的示例。
執行此程式碼
#include <iostream> #include <memory> #include <string> #include <typeindex> #include <typeinfo> #include <unordered_map> struct A { virtual ~A() {} }; struct B : A {}; struct C : A {}; int main() { std::unordered_map<std::type_index, std::string> type_names; type_names[std::type_index(typeid(int))] = "int"; type_names[std::type_index(typeid(double))] = "double"; type_names[std::type_index(typeid(A))] = "A"; type_names[std::type_index(typeid(B))] = "B"; type_names[std::type_index(typeid(C))] = "C"; int i; double d; A a; // note that we're storing pointer to type A std::unique_ptr<A> b(new B); std::unique_ptr<A> c(new C); std::cout << "i is " << type_names[std::type_index(typeid(i))] << '\n'; std::cout << "d is " << type_names[std::type_index(typeid(d))] << '\n'; std::cout << "a is " << type_names[std::type_index(typeid(a))] << '\n'; std::cout << "*b is " << type_names[std::type_index(typeid(*b))] << '\n'; std::cout << "*c is " << type_names[std::type_index(typeid(*c))] << '\n'; }
輸出
i is int d is double a is A *b is B *c is C
[編輯] 另見
包含某些型別資訊的類,由 typeid 運算子返回 (類) |