如何在 C++ 中双向循环迭代 4 个枚举类值?

Luk*_*ich 7 c++ iteration enum-class c++17 c++20

我有:

enum class orientation {
  North,
  East,
  South,
  West
};
Run Code Online (Sandbox Code Playgroud)

我想向左(北 => 西)和向右(西 => 北)旋转它的实例。
但我不想将它们转换为数字,因为它会损害可读性和意图,而且从最后一个数字跳到第一个再跳回很奇怪。

我想出了很多解决方案,但都有些蹩脚:(

Bar*_*rry 9

因为它们是有序的:

constexpr auto rotate(orientation o, int n) -> orientation {
    // convert to int
    int dir = (int)o;
    // rotate as an int
    dir = (dir + n) % 4;
    // account for negatives
    if (dir < 0) {
        dir += 4;
    }
    // and then convert back
    return orientation{dir};
}
Run Code Online (Sandbox Code Playgroud)

您可以检查:

static_assert(rotate(orientation::North, 1) == orientation::East);
static_assert(rotate(orientation::North, -1) == orientation::West);
Run Code Online (Sandbox Code Playgroud)

我选择了整数来表示“向右转 90 度的次数”,但您可以根据实际问题进行调整。或者添加辅助函数,如:

constexpr auto rotate_left(orientation o) -> orientation {
    return rotate(o, -1);
}

constexpr auto rotate_right(orientation o) -> orientation {
    return rotate(o, 1);
}
Run Code Online (Sandbox Code Playgroud)