Created
June 8, 2020 18:07
-
-
Save bugaevc/fc9d76cfbe12122fa6b86e0a80647b9d to your computer and use it in GitHub Desktop.
Get the name of a type as a string, at compile time
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
#include <cstddef> | |
#include <iostream> | |
#include <string_view> | |
template<typename T> | |
static constexpr inline const char *helper1() { | |
// Must have the same signature as helper2(). | |
return __PRETTY_FUNCTION__ + __builtin_strlen(__FUNCTION__); | |
} | |
template<typename T> | |
static constexpr inline const char *helper2() { | |
size_t prefix_len = __builtin_strlen(helper1<void>()) + __builtin_strlen(__FUNCTION__) - 5; | |
return __PRETTY_FUNCTION__ + prefix_len; | |
} | |
template<typename T> | |
static constexpr inline std::string_view type_name() { | |
const char *s = helper2<T>(); | |
return { s, __builtin_strlen(s) - 1 }; | |
} | |
template<typename T> | |
void print_type_name() { | |
std::cout << type_name<T>() << std::endl; | |
} | |
int main() | |
{ | |
print_type_name<int>(); | |
print_type_name<size_t>(); | |
print_type_name<void>(); | |
print_type_name<std::string_view>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment