C++ Get name of type in template

153,302

Solution 1

Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:

template<typename T>
struct TypeParseTraits;
#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
    { static const char* name; } ; const char* TypeParseTraits<X>::name = #X
REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...

And then use it like

throw ParseError(TypeParseTraits<T>::name);

EDIT:

You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable.

Solution 2

The solution is

typeid(T).name()

which returns std::type_info.

Solution 3

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 <string>
#include <cstdlib>
#include <cxxabi.h>
template<typename T>
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;
}

Solution 4

As mentioned by Bunkar typeid(T).name is implementation defined.

To avoid this issue you can use Boost.TypeIndex library.

For example:

boost::typeindex::type_id<T>().pretty_name() // human readable

Solution 5

This trick was mentioned under a few other questions, but not here yet.

All major compilers support __PRETTY_FUNC__ (GCC & Clang) /__FUNCSIG__ (MSVC) as an extension.

When used in a template like this:

template <typename T> const char *foo()
{
    #ifdef _MSC_VER
    return __FUNCSIG__;
    #else
    return __PRETTY_FUNCTION__;
    #endif
}

It produces strings in a compiler-dependent format, that contain, among other things, the name of T.

E.g. foo<float>() returns:

  • "const char* foo() [with T = float]" on GCC
  • "const char *foo() [T = float]" on Clang
  • "const char *__cdecl foo<float>(void)" on MSVC

You can easily parse the type names out of those strings. You just need to figure out how many 'junk' characters your compiler inserts before and after the type.

You can even do that completely at compile-time.


The resulting names can slightly vary between different compilers. E.g. GCC omits default template arguments, and MSVC prefixes classes with the word class.


Here's an implementation that I've been using. Everything is done at compile-time.

Example usage:

std::cout << TypeName<float>() << '\n';
std::cout << TypeName<decltype(1.2f)>(); << '\n';

Implementation: (uses C++20, but can be backported; see the edit history for a C++17 version)

#include <algorithm>
#include <array>
#include <cstddef>
#include <string_view>
namespace impl
{
    template <typename T>
    [[nodiscard]] constexpr std::string_view RawTypeName()
    {
        #ifndef _MSC_VER
        return __PRETTY_FUNCTION__;
        #else
        return __FUNCSIG__;
        #endif
    }
    struct TypeNameFormat
    {
        std::size_t junk_leading = 0;
        std::size_t junk_total = 0;
    };
    constexpr TypeNameFormat type_name_format = []{
        TypeNameFormat ret;
        std::string_view sample = RawTypeName<int>();
        ret.junk_leading = sample.find("int");
        ret.junk_total = sample.size() - 3;
        return ret;
    }();
    static_assert(type_name_format.junk_leading != std::size_t(-1), "Unable to determine the type name format on this compiler.");
    template <typename T>
    static constexpr auto type_name_storage = []{
        std::array<char, RawTypeName<T>().size() - type_name_format.junk_total + 1> ret{};
        std::copy_n(RawTypeName<T>().data() + type_name_format.junk_leading, ret.size() - 1, ret.data());
        return ret;
    }();
}
template <typename T>
[[nodiscard]] constexpr std::string_view TypeName()
{
    return {impl::type_name_storage<T>.data(), impl::type_name_storage<T>.size() - 1};
}
template <typename T>
[[nodiscard]] constexpr const char *TypeNameCstr()
{
    return impl::type_name_storage<T>.data();
}
Share:
153,302
Author by

Carmen

Updated on July 08, 2022

Comments

  • Carmen 11 months

    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, which are for the most part not written by programmers, and so need a nice message about why the app failed to load e.g. something like:

    Error parsing example.txt. Value ("notaninteger")of [MySectiom]Key is not a valid int

    I can work out the file, section and key names from the arguments passed to the template function and member vars in the class, however I'm not sure how to get the name of the type the template function is trying to convert to.

    My current code looks like, with specialisations for just plain strings and such:

    template<typename T> T GetValue(const std::wstring §ion, const std::wstring &key)
    {
        std::map<std::wstring, std::wstring>::iterator it = map[section].find(key);
        if(it == map[section].end())
            throw ItemDoesNotExist(file, section, key)
        else
        {
            try{return boost::lexical_cast<T>(it->second);}
            //needs to get the name from T somehow
            catch(...)throw ParseError(file, section, key, it->second, TypeName(T));
        }
    }
    

    Id rather not have to make specific overloads for every type that the data files might use, since there are loads of them...

    Also I need a solution that does not incur any runtime overhead unless an exception occurs, i.e. a completely compile time solution is what I want since this code is called tons of times and load times are already getting somewhat long.

    EDIT: Ok this is the solution I came up with:

    I have a types.h containg the following

    #pragma once
    template<typename T> const wchar_t *GetTypeName();
    #define DEFINE_TYPE_NAME(type, name) \
        template<>const wchar_t *GetTypeName<type>(){return name;}
    

    Then I can use the DEFINE_TYPE_NAME macro to in cpp files for each type I need to deal with (eg in the cpp file that defined the type to start with).

    The linker is then able to find the appropirate template specialisation as long as it was defined somewhere, or throw a linker error otherwise so that I can add the type.

  • Motti
    Motti almost 14 years
    Keep in mind that it's compliant to return the same string for every type (though I don't think any compiler would do that).
  • Tom Leys
    Tom Leys almost 14 years
    Note: This code will not compile if you forget to define REGISTER_PARSE_TYPE for a type that you use. I have used a similar trick before (in code without RTTI) and it has worked very well.
  • fuzzyTew
    fuzzyTew almost 14 years
    I had to move name outside of the struct in g++ 4.3.0 due to "error: invalid in-class initialization of static data member of non-integral type 'const char *'"; and, of course, the keyword 'struct' is needed between <> and TypeParseTraits and the definition should be terminated with a semicolon.
  • Logan Capaldo
    Logan Capaldo almost 14 years
    Well the leaving the semicolon out was intentional, to force you to use it at the end of the macro invocation, but thanks for the corrections.
  • Emily L.
    Emily L. over 8 years
    Or to return a different string for the same type on different executions... (again not that I think that any sane compiler would do that).
  • kratsg over 8 years
    I obtain the folllowing error: error: '#' is not followed by a macro parameter
  • amdn
    amdn about 8 years
    @kratsg - that's because at the end '#x' should be '#X' (uppercase to match macro parameter) - I'll fix the answer.
  • Tomáš Zato
    Tomáš Zato almost 7 years
    Isn't it memory leak to have free in if?
  • Henry Schreiner
    Henry Schreiner over 6 years
    No, because the pointer points to nullptr if the status is not 0.
  • Fernando
    Fernando almost 6 years
    This is very useful for finding out templates type names when functions are called. It worked pretty well for me.
  • god of llamas
    god of llamas almost 6 years
    I'd like to add that it's probably best to check for gcc or clang's existence and if not default to not doing the demangling as shown here.
  • daminetreg over 5 years
    Note that pretty_name() or raw_name() is still implementation defined. On MSVC for a struct A; you would get : "struct A" while on gcc/clang : "A".
  • Trevor Boyd Smith
    Trevor Boyd Smith about 5 years
    wow. boost again for the win. amazing what boost does without compiler support (auto, regex, foreach, threads, static_assert, etc, etc... support before compilers/C++-standard support).
  • Andreas detests censorship
    Andreas detests censorship over 4 years
    I'd just like to point out how ugly the given name can be: typeid(simd::double3x4).name() = "N4simd9double3x4E". typeid(simd::float4).name() = "Dv4_f" C++17, Xcode 10.1.
  • Justin Time - Reinstate Monica
    Justin Time - Reinstate Monica over 3 years
    Indeed. typeid(T).name() is the canonical way to do this, but very few compilers return unmangled names; the only one I'm personally familiar with that does so is MSVC. Depending on the compiler used, there's also a chance that it may lose some type information on function types, but that's probably irrelevant in this case.
  • Little Helper
    Little Helper over 2 years
    This is great, but why not do return #type; instead?
  • jpo38
    jpo38 over 2 years
    @LittleHelper: You are right, that would also work...
  • lmat - Reinstate Monica
    lmat - Reinstate Monica over 2 years
    typeid(T).name() does not return std::type_info, but char const *.
  • György Gulyás
    György Gulyás over 1 year
    THAT is the real answer!! Absolutly beatifull, no need std lib, and it runs complie time. In embedded code, this is the only solution. Thank you!!
  • eclarkso about 1 year
    I like this answer as well, but beware GCC < 8.0 does not define __PRETTY_FUNCTION__ as a constexpr - which is on the default gcc on Ubuntu 18. Also, here is a similar-in-concept implementation (also based on __PRETTY_FUNCTION__).