Print template typename at compile time

后端 未结 6 1180
予麋鹿
予麋鹿 2020-12-08 09:41

When creating a template function in C++ is there a simple way to have the typename of the template represented as a string? I have a simple test case to show what I\'m try

6条回答
  •  广开言路
    2020-12-08 10:04

    Since you have said you would need this for debugging purpose, maybe a runtime solution is also acceptable. And you have tagged this as g++ so you don't want to be standard conform.

    Here is what that means:

    #include  // the libstdc++ used by g++ does contain this header
    
    template 
    void print(const type *addr) // you wanted a pointer
    {
      char * name = abi::__cxa_demangle(typeid(*addr).name(), 0, 0, NULL);
      printf("type is: %s\n", name);
      delete name;
    }
    
    print(new unsigned long);    // prints "type is: unsigned long"
    print(new std::vector); // prints "type is: std::vector >"
    

    EDIT: corrected the memory leak. Thx to Jesse.

提交回复
热议问题