Last active
January 6, 2024 12:42
-
-
Save pmttavara/54b60ba5310db6e38f5b0093be320ad9 to your computer and use it in GitHub Desktop.
Using "functional X macro" for metaprogramming-like enum name extraction
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 <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