Skip to content

Instantly share code, notes, and snippets.

@cppio
Created February 15, 2019 02:17
Show Gist options
  • Select an option

  • Save cppio/cf371a6b140d701c5e5c9bb452a3be55 to your computer and use it in GitHub Desktop.

Select an option

Save cppio/cf371a6b140d701c5e5c9bb452a3be55 to your computer and use it in GitHub Desktop.
Templated C++ function to get the demangled name of a type with const, volatile, and references.
#include <cxxabi.h>
#include <typeinfo>
#include <type_traits>
#include <string>
#include <memory>
#include <cstdlib>
template<typename T>
std::string type_name() {
std::unique_ptr<char, decltype(&std::free)> demangled(
abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, nullptr),
std::free
);
std::string name = demangled ? demangled.get() : typeid(T).name();
if (std::is_const<T>::value) name += " const";
if (std::is_volatile<T>::value) name += " volatile";
if (std::is_lvalue_reference<T>::value) name += "&";
else if (std::is_rvalue_reference<T>::value) name += "&&";
return name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment