Last active
August 6, 2021 08:07
-
-
Save DBJDBJ/6d02e202ac3f32db59106981a10edaff to your computer and use it in GitHub Desktop.
C++ linux demangler for clang ang gcc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
(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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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