Skip to content

Instantly share code, notes, and snippets.

@DBJDBJ
Last active August 6, 2021 08:07
Show Gist options
  • Save DBJDBJ/6d02e202ac3f32db59106981a10edaff to your computer and use it in GitHub Desktop.
Save DBJDBJ/6d02e202ac3f32db59106981a10edaff to your computer and use it in GitHub Desktop.
C++ linux demangler for clang ang gcc
/*
(c) 2018-2021 by [email protected] -- https://dbj.org/license_dbj
usage:
auto demangled_name = dbj::demang< int (&) [42] >() ;
This is both windows and linux code.
https://godbolt.org/z/7bTxazhTv
*/
#ifndef _WIN32
#include <cxxabi.h>
#endif
namespace dbj {
#ifdef _WIN32
template <typename T>
const char* demang() noexcept {
static auto demangled_name = []() { return {typeid(T).name()}; }();
return demangled_name.data();
}
#else // __linux__
template <typename T>
const char* demang() noexcept {
// once per one type
static auto demangled_name = []() {
int error = 0;
std::string retval;
char* name = abi::__cxa_demangle(typeid(T).name(), 0, 0, &error);
switch (error) {
case 0:
retval = name;
break;
case -1:
retval = "memory allocation failed";
break;
case -2:
retval = "not a valid mangled name";
break;
default:
retval = "__cxa_demangle failed";
break;
}
std::free(name);
return retval;
}();
// std::free(name) ;
return demangled_name.data();
}
#endif // __linux__
// calling with instances
template <typename T>
const char* demang(T const&) noexcept {
return demang<T>();
}
} // namespace dbj
@DBJDBJ
Copy link
Author

DBJDBJ commented Aug 6, 2021

Note the optimization vs the previous version. Since one type has one name for the lifetime of a program above we do that only once and not before requested.

Current version demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment