C++ 循环枚举值的实现
实现具有循环值的枚举以及从一个值转换到另一个值的适当函数的最佳方法是什么 例如:C++ 循环枚举值的实现,c++,c++11,enums,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); } enum类方向{ 北、东、南、西 }; constex
enum class Direction {
NORTH, EAST, SOUTH, WEST
};
constexpr Direction left(Direction d) {
return (Direction)((std::underlying_type<Directions>::type(d) - 1) % 4);
}
enum类方向{
北、东、南、西
};
constexpr方向左(方向d){
返回(方向)((标准::基本类型::类型(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));
}
enum类方向{
北、东、南、西、多个方向
};
constexpr方向左(方向d){
使用ut=std::底层_type::type;
返回(方向)((ut(d)+ut(方向::方向的数量)-1)
%ut(方向:方向的数量);
}
使用示例/小型测试:
#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);
}
}
#包括
std::ostream&operator使用四格switch语句显式地将其清除?这将是最具可读性的选项。如果有更多的值呢?如果将left
更改为nextCountorclockwise
(或者简而言之nextcw
)-DIt甚至不需要额外的元素,只需执行%(std::underlined_type::type(WEST)+1)
。但是,它看起来确实像一个快速解决方案,不是吗?@Svalorzen:是的,但是WEST+1
并不是真正的人类可读的。如果在WEST
之后添加了内容,会发生什么情况?至少在方向数方面
它的意图是明确的。@PeterK。尽管如此,您仍然需要将整个基本类型
转换为方向数
,因此它会变得相当长,而且也不那么可读。这是一个很好的技巧!它增加了函数的可读性,但降低了枚举的可读性。@PeterK。这个实现怎么样?加号可能会溢出,但我认为不太可能(整体促销)。
NORTH
WEST
SOUTH
EAST
NORTH
WEST
SOUTH
EAST