C++ Get name of type in template

后端 未结 10 2150
天涯浪人
天涯浪人 2020-11-27 11:28

I\'m writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, whic

10条回答
  •  鱼传尺愫
    2020-11-27 12:03

    typeid(T).name() is implementation defined and doesn't guarantee human readable string.

    Reading cppreference.com :

    Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

    ...

    With compilers such as gcc and clang, the returned string can be piped through c++filt -t to be converted to human-readable form.

    But in some cases gcc doesn't return right string. For example on my machine I have gcc whith -std=c++11 and inside template function typeid(T).name() returns "j" for "unsigned int". It's so called mangled name. To get real type name, use abi::__cxa_demangle() function (gcc only):

    #include 
    #include 
    #include 
    
    template
    std::string type_name()
    {
        int status;
        std::string tname = typeid(T).name();
        char *demangled_name = abi::__cxa_demangle(tname.c_str(), NULL, NULL, &status);
        if(status == 0) {
            tname = demangled_name;
            std::free(demangled_name);
        }   
        return tname;
    }
    

提交回复
热议问题