|
C++ 在設計時有時會需要變數類別,或者類別名稱,這邊整理並實際測試幾個方法。 |
---|
typeid
typeid 是一種運算子,用來查看變數是屬於何種類別、型態,或是結構,基本的使用範例可以參考下述 C++ code:
#include <iostream> class NormalHunter { public: void introduce() { std::cout << "This is normal hunter." << std::endl; } }; int main(int argc, char* argv[]) { NormalHunter normal_hunter; int tmp_integer = 10; int* tmp_pointer = new int(12); normal_hunter.introduce(); std::cout << "Typename of normal_hunter: " << typeid(normal_hunter).name() << std::endl; std::cout << "Typename of tmp_integer: " << typeid(tmp_integer).name() << std::endl; std::cout << "Typename of tmp_pointer: " << typeid(tmp_pointer).name() << std::endl; system("pause"); }
透過 method name() 可以得到 char array,其顯示結果應該如下:
This is normal hunter. Typename of normal_hunter: class NormalHunter Typename of tmp_integer: int Typename of tmp_pointer: int *
decltype
參考資料
- typeid operator,cppreference.com
- static_cast and typeid,cplusplus.com,2011
- C++ - Is there a way that using Class name as a key of std::map?,stackoverflow,2011
No comments:
Post a Comment