Skip to content

Instantly share code, notes, and snippets.

@Supercip971
Created May 27, 2023 18:20
Show Gist options
  • Save Supercip971/d42e58d3cadc677de1dc7d77347aba14 to your computer and use it in GitHub Desktop.
Save Supercip971/d42e58d3cadc677de1dc7d77347aba14 to your computer and use it in GitHub Desktop.
A quick way of transforming an Enum to string inC++
// Type your code here, or load an example.
#include <stdio.h>
#include <string>
struct Str
{
const char* base;
size_t len;
operator std::string() const
{
return std::string(base, base+len);
}
};
template<typename T, const T V>
constexpr Str enum_to_str_impl()
{
const char* v= __PRETTY_FUNCTION__;
while(*v != ';' && *v != ','&& *v != 0)
{
v++;
}
while(*v != '=' && *v != 0)
{
v++;
}
v++; // escape '='
v++; // escape ' '
Str s = (Str){
.base = v,
.len = 0
};
int l = 0;
while(*v != 0 && *v != ']')
{
v++;
l++;
}
s.len = l;
return s;
};
#define mdef$(t, v) enum_to_str_impl<t, static_cast<t>(v)>()
#define mdefc$(t, v) enum_to_str_impl<t, static_cast<t>(v)>(),
#define mloop1_5(x, t, v) x(t,v + 0) x(t,v+1) x(t,v+2) x(t,v+3) x(t,v+4)
#define mloop2_5(x, t, v) mloop1_5(x,t,(v)*5 + 0) mloop1_5(x,t,(v+1)*5) mloop1_5(x,t,(v+2)*5) mloop1_5(x,t,(v+3)*5) mloop1_5(x,t,(v+4)*5)
#define mloop3_5(x, t, v) mloop2_5(x,t,(v)*5 + 0) mloop2_5(x,t,(v+1)*5) mloop2_5(x,t,(v+2)*5) mloop2_5(x,t,(v+3)*5) mloop2_5(x,t,(v+4)*5)
#define mloop4_5(x, t, v) mloop3_5(x,t,(v)*5 + 0) mloop3_5(x,t,(v+1)*5) mloop3_5(x,t,(v+2)*5) mloop3_5(x,t,(v+3)*5) mloop3_5(x,t,(v+4)*5)
#define mloop5_5(x, t, v) mloop4_5(x,t,(v)*5 + 0) mloop4_5(x,t,(v+1)*5) mloop4_5(x,t,(v+2)*5) mloop4_5(x,t,(v+3)*5) mloop4_5(x,t,(v+4)*5)
template<typename T> \
constexpr Str enum_to_str(T value) {
return (Str){ \
"",
0
};
};
#define enum2str_def125$(t) \
template<> \
constexpr Str enum_to_str<t>(t value) {\
constexpr Str v[] = {mloop4_5(mdefc$, t, 0)};\
if(value > sizeof(v) / sizeof(v[0])) \
{\
return (Str){ \
"", \
0 \
}; \
} \
return v[static_cast<int>(value)]; \
};
#define enum2str_def625$(t) \
template<> \
constexpr Str enum_to_str<t>(t value) {\
constexpr Str v[] = {mloop4_5(mdefc$, t, 0)};\
if(value > sizeof(v) / sizeof(v[0])) \
{\
return (Str){ \
"", \
0 \
}; \
} \
return v[static_cast<int>(value)]; \
};
#define enum2str_def3125$(t) \
template<> \
constexpr Str enum_to_str<t>(t value) {\
constexpr Str v[] = {mloop5_5(mdefc$, t, 0)};\
if(value > sizeof(v) / sizeof(v[0])) \
{\
return (Str){ \
"", \
0 \
}; \
} \
return v[static_cast<int>(value)]; \
};
#define enum2str_def$(t) enum2str_def625$(t)
enum Colors : int
{
NONE,
RED,
BLUE
};
enum2str_def$(Colors);
/*
void print_str(Str v){
for(int i = 0; i < v.len; i++)
{
printf("%c", v.base[i]);
}
}
int main()
{
Str v = mdef$(Colors, 1);
for(int i = 0; i < 69; i++)
{
printf("%i = ", i);
print_str(enum_to_str<Colors>(static_cast<Colors>(i)));
printf("\n");
}
printf("\n");
return 0;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment