目前,我在一个小游戏实验中使用枚举来表示状态.我这样宣告他们:
Currently I'm using enums to represent a state in a little game experiment. I declare them like so:
namespace State { enum Value { MoveUp = 1 << 0, // 00001 == 1 MoveDown = 1 << 1, // 00010 == 2 MoveLeft = 1 << 2, // 00100 == 4 MoveRight = 1 << 3, // 01000 == 8 Still = 1 << 4, // 10000 == 16 Jump = 1 << 5 }; }这样我就可以这样使用它们:
So that I can use them this way:
State::Value state = State::Value(0); state = State::Value(state | State::MoveUp); if (mState & State::MoveUp) movement.y -= mPlayerSpeed;但是我想知道这是否是实现位标志的正确方法.是否没有用于存放位标志的特殊容器?我听说过std::bitset,这是我应该使用的吗?您知道更有效的方法吗? 我做对了吗?
But I'm wondering if this is the right way to implement bit flags. Isn't there a special container for bit flags? I heard about std::bitset, is it what I should use? Do you know something more efficient? Am I doing it right?
我忘了指出我正在重载枚举的基本运算符:
I forgot to point out I was overloading the basic operators of my enum:
inline State::Value operator|(State::Value a, State::Value b) { return static_cast<State::Value>(static_cast<int>(a) | static_cast<int>(b)); } inline State::Value operator&(State::Value a, State::Value b) { return static_cast<State::Value>(static_cast<int>(a) & static_cast<int>(b)); } inline State::Value& operator|=(State::Value& a, State::Value b) { return (State::Value&)((int&)a |= (int)b); }我必须对|=使用C样式的强制转换,它与static_cast不能一起使用-知道为什么吗?
I had to use a C-style cast for the |=, it didn't work with a static_cast - any idea why?
推荐答案我认为您的方法是正确的(除了几件事): 1.您可以显式指定基础类型以节省内存; 2.您不能使用未指定的枚举值.
I believe that your approach is right (except several things): 1. You can explicitly specify underlying type to save memory; 2. You can not use unspecified enum values.
namespace State { enum Value : char { None = 0, MoveUp = 1 << 0, // 00001 == 1 MoveDown = 1 << 1, // 00010 == 2 MoveLeft = 1 << 2, // 00100 == 4 MoveRight = 1 << 3, // 01000 == 8 Still = 1 << 4, // 10000 == 16 Jump = 1 << 5 }; }和:
State::Value state = State::Value::None; state = State::Value(state | State::MoveUp); if (mState & State::MoveUp) { movement.y -= mPlayerSpeed; }关于超载:
inline State::Value& operator|=(State::Value& a, State::Value b) { return a = static_cast<State::Value> (a | b); }由于您使用的是C ++ 11,因此应该使用constexpr每种可能的方法:
and since you use C++11, you should use constexpr every were is possible:
inline constexpr State::Value operator|(State::Value a, State::Value b) { return a = static_cast<State::Value> (a | b); } inline constexpr State::Value operator&(State::Value a, State::Value b) { return a = static_cast<State::Value> (a & b); }更多推荐
枚举是实现位标志的规范方法吗?
发布评论