Last active
March 26, 2022 16:43
-
-
Save dgodfrey206/42260acec9c9d6300a0b to your computer and use it in GitHub Desktop.
ToString for arbitrary types
This file contains hidden or 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 <iostream> | |
#include <cstring> | |
#define TO_STRING_FOR_CLASS(X)\ | |
template<class T>\ | |
const char* ToString();\ | |
\ | |
template<>\ | |
const char* ToString<X>() {\ | |
static const char* str = #X;\ | |
static std::size_t len = strlen(str);\ | |
if (len > 4) {\ | |
if (strncmp(str, "enum", 4) == 0) {\ | |
str += 4 + 1;\ | |
}\ | |
if (len > 5) {\ | |
if (strncmp(str, "class", 5) == 0 || strncmp(str, "union", 5) == 0) {\ | |
str += 5 + 1;\ | |
}\ | |
else if (strncmp(str, "struct", 6) == 0) {\ | |
str += 6 + 1;\ | |
}\ | |
}\ | |
}\ | |
return str;\ | |
} | |
TO_STRING_FOR_CLASS(class Apple); | |
TO_STRING_FOR_CLASS(struct Bubbles); | |
TO_STRING_FOR_CLASS(union School); | |
template<class T> | |
void f() { | |
std::cout << "You passed in the type: " << ToString<T>() << '\n'; | |
} | |
int main() { | |
f<Apple>(); | |
f<Bubbles>(); | |
f<School>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment