循环枚举值的实现

时间:2013-04-20 20:32:47

标签: c++ c++11 enums

使用循环值实现枚举的最佳方法是什么,以及从值转换到另一个值的适当函数是什么?

例如:

enum class Direction {
    NORTH, EAST, SOUTH, WEST
};

constexpr Direction left(Direction d) {
    return (Direction)((std::underlying_type<Directions>::type(d) - 1) % 4);
}

但是,我觉得这很容易出错并且通常不可读。有没有更合适的方法来处理这种类型的枚举?

1 个答案:

答案 0 :(得分:9)

你总是可以这样做:

enum class Direction {
    NORTH, EAST, SOUTH, WEST, NUMBER_OF_DIRECTIONS
};

constexpr Direction left(Direction d) {
    using ut = std::underlying_type<Direction>::type;
    return (Direction)((ut(d) + ut(Direction::NUMBER_OF_DIRECTIONS)-1)
                       % ut(Direction::NUMBER_OF_DIRECTIONS));
}

用法示例/小测试:

#include <iostream>

std::ostream& operator<<(std::ostream& os, Direction d)
{
    switch(d)
    {
        case Direction::NORTH: return os << "NORTH";
        case Direction::EAST : return os << "EAST";
        case Direction::SOUTH: return os << "SOUTH";
        case Direction::WEST : return os << "WEST";
        default              : return os << "invalid";
    }
}

int main()
{
    Direction d = Direction::NORTH;
    for(int i = 0; i < 2*(int)Direction::NUMBER_OF_DIRECTIONS; ++i)
    {
        std::cout << d << "\n";
        d = left(d);
    }
}

输出:

NORTH
WEST
SOUTH
EAST
NORTH
WEST
SOUTH
EAST

Live example