gpt4 book ai didi

c++ - 循环枚举值的实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:21:50 26 4
gpt4 key购买 nike

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

例如:

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

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

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

最佳答案

你总是可以这样做:

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);
}
}

输出:

NORTHWESTSOUTHEASTNORTHWESTSOUTHEAST

Live example

关于c++ - 循环枚举值的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16124897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com