我有:
enum class orientation {
North,
East,
South,
West
};
我想向左(北 => 西)和向右(西 => 北)旋转它的实例。
但我不想将它们转换为数字,因为它会损害可读性和意图,而且从最后一个数字跳到第一个再跳回很奇怪。
我想出了很多解决方案,但都有些蹩脚:(
最佳答案
因为它们是有序的:
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};
}
您可以检查:
static_assert(rotate(orientation::North, 1) == orientation::East);
static_assert(rotate(orientation::North, -1) == orientation::West);
我选择了整数来表示“向右转 90 度的次数”,但您可以根据实际问题进行调整。或者添加辅助函数,如:
constexpr auto rotate_left(orientation o) -> orientation {
return rotate(o, -1);
}
constexpr auto rotate_right(orientation o) -> orientation {
return rotate(o, 1);
}
关于c++ - 如何在 C++ 中双向循环迭代 4 个枚举类值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61374507/