循环枚举值的实现

Sva*_*zen 6 c++ enums c++11

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

例如:

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

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

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

Pet*_* K. 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));
}
Run Code Online (Sandbox Code Playgroud)

用法示例/小测试:

#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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

NORTH
WEST
SOUTH
EAST
NORTH
WEST
SOUTH
EAST

实例