Skip to content

Instantly share code, notes, and snippets.

@pmttavara
Last active January 6, 2024 12:42
Show Gist options
  • Save pmttavara/54b60ba5310db6e38f5b0093be320ad9 to your computer and use it in GitHub Desktop.
Save pmttavara/54b60ba5310db6e38f5b0093be320ad9 to your computer and use it in GitHub Desktop.
Using "functional X macro" for metaprogramming-like enum name extraction
#include <string.h> // for strcmp
#define Enum_Member(Name, Value) Name = Value,
#define Enum_To_String(Name, Value) if (e == Name) return # Name;
#define Enum_From_String(Name, Value) if (strcmp(str, # Name) == 0) return Name;
#define Define_Enum(EnumName) \
\
enum EnumName { \
EnumName(Enum_Member) \
}; \
\
inline const char * EnumName ## _to_string(EnumName e) { \
EnumName(Enum_To_String); \
/* unknown enum value -- maybe do smarter error handling here */ \
return ""; \
} \
\
inline EnumName EnumName ## _from_string(const char *str) { \
EnumName(Enum_From_String); \
/* no string matched -- maybe do smarter error handling here */ \
return (EnumName)0; \
}
// ... Sample usage:
// Here is the actual enum definition:
#define Flags(X) \
X(Wireframe, 1 << 0) \
X(CullFrontFaces, 1 << 1) \
X(CullBackFaces, 1 << 2)
Define_Enum(Flags);
#include <stdio.h> // for printf
int main() {
printf("to_string(Wireframe) is %s\n", Flags_to_string(Wireframe));
printf("from_string(Wireframe) is %d\n", Flags_from_string("Wireframe"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment