Aug 3, 2026

[C++26] Reflection minute


#include <iostream>

// 1. Define the master list of colors (X Macro)
// This is the single source of truth. Adding a color here 
// automatically updates both the enum and the string converter below.
#define COLORS \
    FUNC(Red)  \
    FUNC(Blue) \
    FUNC(Green)

// 2. Generate the Enum Class
enum class Color {
#define FUNC(name) name,
    COLORS
#undef FUNC
};

// 3. Generate a Helper Function to convert Enum to String using '#' (stringification)
const char* ColorToString(Color color) {
    switch (color) {
#define FUNC(name) case Color::name: return #name;
        COLORS
#undef FUNC
        default: return "Unknown";
    }
}

int main() {
    // Instantiate color variables
    Color r = Color::Red;
    Color b = Color::Blue;
    Color g = Color::Green;

    // Output and verify the mapping works correctly
    std::cout << "Color r is: " << ColorToString(r) << " (Enum value: " << static_cast<int>(r) << ")\n";
    std::cout << "Color b is: " << ColorToString(b) << " (Enum value: " << static_cast<int>(b) << ")\n";
    std::cout << "Color g is: " << ColorToString(g) << " (Enum value: " << static_cast<int>(g) << ")\n";

    return 0;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.