枚举是实现位标志的规范方法吗?

编程入门 行业动态 更新时间:2024-10-26 23:41:49
本文介绍了枚举是实现位标志的规范方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

目前,我在一个小游戏实验中使用枚举来表示状态.我这样宣告他们:

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

更多推荐

枚举是实现位标志的规范方法吗?

本文发布于:2023-10-07 17:09:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标志   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!