I recently had the need to retrieve the type of a template argument as a human-readable string for debugging purposes, but without using RTTI – so typeid and type_info were out of the question.

After a bit of trial and error, I came up with the following solution. I thought it was a nice little self-contained piece of code, so I wanted to share it with everybody:

namespace internal { static const unsigned int FRONT_SIZE = sizeof("internal::GetTypeNameHelper<") - 1u; static const unsigned int BACK_SIZE = sizeof(">::GetTypeName") - 1u; template <typename T> struct GetTypeNameHelper { static const char* GetTypeName(void) { static const size_t size = sizeof(__FUNCTION__) - FRONT_SIZE - BACK_SIZE; static char typeName[size] = {}; memcpy(typeName, __FUNCTION__ + FRONT_SIZE, size - 1u); return typeName; } }; } template <typename T> const char* GetTypeName(void) { return internal::GetTypeNameHelper<T>::GetTypeName(); }

Under MSVC, this nicely yields the following:

struct Foo {}; class Bar {}; GetTypeName<int>() -> "int" GetTypeName<float>() -> "float" GetTypeName<Foo>() -> "struct Foo" GetTypeName<Bar>() -> "class Bar"

It should be straightforward to understand how the code works. The only thing worth mentioning is that we defer the actual implementation to a static function inside a class template, in order to make the type T become a part of __FUNCTION__. Otherwise, __FUNCTION__ will expand to “GetTypeName”, not including the actual type of the provided T.

The code provided above works with MSVC and Clang. Under GCC, you need to use __PRETTY_FUNCTION__ and adapt FRONT_SIZE and BACK_SIZE accordingly.

Note that, unfortunately, we have to resort to __FUNCTION__ and __PRETTY_FUNCTION__ and cannot use __func__ as described by the C++11 standard, because even __func__ is specified as containing an implementation-defined string. And in the case of the compilers I tested, __func__ evaluates to “GetTypeName”, not including any information about T.