Thursday, 29 December 2011

Namespaced enums (2)

A short follow-on to yesterday's post.

One additional advantage of the namespaced version over enum classes is that you have a namespace for populating with useful enum-related functions, for example:

namespace Direction
{
    enum type
    {
        Left,
        Right,
        Up,
        Down
    };

    const char* names[] = { "Left", "Right", "Up", "Down" };

    inline const char* to_ascii(type e)
    {
        return names[e];
    }

    type from_ascii(const char* c)
    {
        for (int i = 0; i != sizeof(names)/sizeof(names[0]); ++i)
            if (!strcmp(c, names[i]))
                return (type)i;

        throw conversion_error_exception();
    }
};

auto e  = Direction::Up;
auto a  = to_ascii(e);
auto e2 = Direction::from_ascii(a);

No comments:

Post a Comment