C++返回一個變量類型的名稱


typeid關鍵字

頭文件:

1 #include<typeinfo>

 

運行時獲知變量類型名稱,可以使用 typeid(變量).name()

但它的返回值是取決於編譯器的,比如對於g++來說只會返回類型名稱的首字母:

 

 

 

 

 這時就要用到另一個東東:

 

1 abi::__cxa_demangle(typeid(x).name(),0,0,0)

 

需要的頭文件:

1 #include<cxxabi.h>

 

 

打包一下:

(typeof竟然是關鍵字……)

 1 #include<iostream>  2 #include<typeinfo>  3 #include<cxxabi.h>  4  5 using namespace std;  6  7 template<typename type>  8 inline string type_of(type &x)  9 { 10 return abi::__cxa_demangle(typeid(x).name(),0,0,0); 11 }

 

效果如下

 

 

 

 

 

 如果你要深入研究,可以看看這個dalao的博客(戳我)~

下面是一些栗子: 

 

 1 #include<iostream>  2 #include<typeinfo>  3 #include<cxxabi.h>  4  5 using namespace std;  6  7 template<typename type>  8 inline string type_of(type &x)  9 { 10 return abi::__cxa_demangle(typeid(x).name(),0,0,0); 11 } 12 13 unsigned long long a; 14 static short b; 15 __int128 c; 16 17 inline void d(int e,float f) 18 { 19 return; 20 } 21 22 struct node{ 23 char g; 24 char h[100]; 25  signed i; 26 }j[200]; 27 28 int k; 29 int *l=&k; 30 int **m=&l; 31 32 signed main() 33 { 34 register int n;//寄存器變量只能在棧空間中使用  35 cout<<"a: "<<type_of(a)<<endl; 36 cout<<"b: "<<type_of(b)<<endl; 37 cout<<"c: "<<type_of(c)<<endl; 38 cout<<"d: "<<type_of(d)<<endl; 39 cout<<"j: "<<type_of(j)<<endl; 40 cout<<"j[1].g: "<<type_of(j[1].g)<<endl; 41 cout<<"j[100].h: "<<type_of(j[100].h)<<endl; 42 cout<<"j[201].h[101]: "<<type_of(j[201].h[101])<<endl; 43 cout<<"j[201].i: "<<type_of(j[201].i)<<endl; 44 cout<<"k: "<<type_of(k)<<endl; 45 cout<<"l: "<<type_of(l)<<endl; 46 cout<<"m: "<<type_of(m)<<endl; 47 cout<<"n: "<<type_of(n)<<endl; 48 return 0; 49 }

 輸出:

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM