验证整数是某个枚举类项 (C++11)
我有一些枚举类,
enum class Foo { A=1, B=18 , Z=42 };
我想检查某些整数是否可以转换为 Foo
。 做到这一点的理想方法是什么?这是用于运行时检查(在编译时尚不知道整数)
显然我可以用困难的方式做到这一点(编写一个函数 bool CheckEnum(Foo);
并使用返回 true 的大开关对于除默认情况之外的所有情况),但我希望有一种更优雅的机制来避免大量编写。 MPL 或 Boost.Preprocessor 是一个完全可以接受的解决方案,但遗憾的是我对其中一个知之甚少
i have some enum class
enum class Foo { A=1, B=18 , Z=42 };
i want to check if some integer can be converted into a Foo
.
What would be the ideal way to do this? this is for runtime check (the integer is not known yet at compile-time)
Obviously i can do this the hard way (write a function bool CheckEnum(Foo);
with a big-ass switch returning true for all cases except the default one), but i was hoping a more elegant mechanism that avoided so much writing. MPL or Boost.Preprocessor
would be a perfectly acceptable solution, but one of which i sadly know very little about
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此问题的解决方案是放弃枚举,并将其替换为使用 XMACRO 创建的一些数组。
A solution to this problem is to ditch the enums, and replace it with some arrays which are created using XMACROs.
没有“理想”的方法可以做到这一点。所有方法都必须涉及一些手工工作。
您需要创建一个包含所有可接受值的数据结构。然后用您需要的运行时值搜索该数据结构。
std::set
或std::unordered_set
足以满足此目的。您的主要困难在于维护该列表,因为每次更改
枚举类
时都需要更新它。There is no "ideal" way to do it. All ways are going to have to involve some manual work.
You need to create a data structure that contains all of the acceptable values. Then search that data structure with the runtime value you need. A
std::set
orstd::unordered_set
would be adequate for this purpose.Your main difficulty will be in maintaining that list, as it will need to be updated every time you change your
enum class
.好吧,我有点厌倦了这个问题(我的一些枚举有近 100 项)
所以我决定通过代码生成来解决这个问题,这可能不是每个人都喜欢的,但我意识到这确实没什么大不了的。
基本上我选择了 Python Cog,它允许我在 .h 和 . cpp 文件并自动生成代码。我基本上就像一个非常智能的命令式宏系统一样使用它:
我将以下内容添加到
Test.h
然后我在 Makefile 预构建步骤中添加了 cog 调用:
结果显示在下面
: ,现在我的枚举验证是为了确保代码生成(在编译时调用)正确完成
Ok i'm a little bit fed up with this issue (some of my enums are nearly 100 items)
so i decided to tackle it with code generation, which might not be everyone's cup of tea, but i've realised that is really no such a big deal.
Basically i went for Python Cog, which allows me to embed python snippets inside comments in my .h and .cpp files and auto-generate code. I use it basically like a really smart, imperative macro system:
i added the following to
Test.h
Then i added cog invocation in my Makefile pre-build step:
And the results show up just below:
So, now my enum validation is about making sure the code generation (invoked at compile time) is done correctly