Aug 20, 2015

[C++][Enum Macro]

from reddit:
----------
#define STRONG_ENUM(Name, ...) \
    class Name { \
    public: \
        enum Name##_ { \
            __VA_ARGS__ \
        }; \
    public: \
        Name(Name::Name##_ v) : mValue(v) {} \
        operator Name::Name##_() const { return mValue; } \
        Name& operator=(Name::Name##_ v) { \
            mValue = v; \
            return *this; \
        } \
    private: \
        Name::Name##_ mValue; \
    }

usage:
STRONG_ENUM(Color,
    Red,
    Green,
    Blue
);

const char* tostring(Color c) {
    switch(c) {
    case Color::Red:
        return "red";
    case Color::Green:
        return "green";
    case Color::Blue:
        return "blue";
    }
}

Color c = Color::Red;
std::cout << tostring(c) << std::endl;

No comments:

Post a Comment

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