C++返回一个变量类型的名称

  • typeid关键字

    • 头文件:#include<typeinfo>

    • 获取变量类型名称:typeid(变量).name()

    • 返回值:取决于编译器

      比如对于g++来说只会返回变量类型名称的首字母:

如需获取变量类型完整名称,则需要:

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

    • 头文件:#include<cxxabi.h>

    • 代码

      #include<iostream>
      #include<typeinfo>
      #include<cxxabi.h>
      
      using namespace std;
      
      template<typename type>
      inline string type_of(type &x)//typeof竟然是关键字......
      {
          return abi::__cxa_demangle(typeid(x).name(),0,0,0);
      }
      
    • 效果

若想深入研究,可以参考这个博客

  • 一些栗子

    #include<iostream>
    #include<typeinfo>
    #include<cxxabi.h>
    
    using namespace std;
    
    template<typename type>
    inline string type_of(type &x)
    {
        return abi::__cxa_demangle(typeid(x).name(),0,0,0);
    }
    
    unsigned long long a;
    static short b;
    __int128 c;
    
    inline void d(int e,float f)
    {
        return;
    }
    
    struct node{
        char g;
        char h[100];
        signed i;
    }j[200];
    
    int k;
    int *l=&k;
    int **m=&l;
    
    signed main()
    {
        register int n;//寄存器变量只能在栈空间中使用 
        cout<<"a:  "<<type_of(a)<<endl;
        cout<<"b:  "<<type_of(b)<<endl;
        cout<<"c:  "<<type_of(c)<<endl;
        cout<<"d:  "<<type_of(d)<<endl;
        cout<<"j:  "<<type_of(j)<<endl;
        cout<<"j[1].g:  "<<type_of(j[1].g)<<endl;
        cout<<"j[100].h:  "<<type_of(j[100].h)<<endl;
        cout<<"j[201].h[101]:  "<<type_of(j[201].h[101])<<endl;
        cout<<"j[201].i:  "<<type_of(j[201].i)<<endl;
        cout<<"k:  "<<type_of(k)<<endl;
        cout<<"l:  "<<type_of(l)<<endl;
        cout<<"m:  "<<type_of(m)<<endl;
        cout<<"n:  "<<type_of(n)<<endl;
        return 0;
    }
    

    输出:

posted @ 2021-08-29 17:46  凌云_void  阅读(1038)  评论(1编辑  收藏  举报