C++11:从旧式枚举迁移到枚举类的正确方法是什么?
我目前正在将代码从旧式枚举迁移到枚举类。
强类型很好,但我在代码中遇到了一个点,我需要调用 ncurses 的 init_pair() 函数,该函数将 short int
作为其第一个参数,但我已将其转换为供开发人员阅读的枚举类。
为了让编译器满意,我似乎需要在第一个参数上使用 static_cast
。
有没有更干净的方法或者如果我必须使用 static_cast,您建议我如何使用它?
接受的答案:克里斯·多德的答案很好。在切换之前,我到处都有代表旧式枚举的整数。切换之后,我在代码的其余部分中使用了类型安全枚举的脏类型转换。肮脏的地方被隔离到一处,代码更安全,也更容易阅读。这是一个显着的进步。
I am currently migrating my code from the old-style enum to enum class.
The strong-typing is nice, but I came across a point in the code where I needed to call ncurses's init_pair() function which takes a short int
as its first argument, but which I have converted to an enum class for developer-friendly reading.
To make the compiler happy, it seems that I need to use a static_cast<short int>()
on the first parameter.
Is there a cleaner approach or if I must use the static_cast, how do you recommend that I use it?
Accepted Answer: Chris Dodd's answer is good. Before the switch, I had ints all over the place representing the old-style enums. After the switch, I have one dirty cast with type-safe enums all over the rest of the code. The dirtiness is isolated to one spot, the code is safer, and it's easier to read. This is a marked improvement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最干净的方法可能是定义 init_pair 的重载内联版本,它采用枚举并将其转换为调用普通版本:
这样用户可以使用枚举类型调用它,并且它将正常工作
The cleanest way is probably to define an overloaded inline version of init_pair that takes an enum and casts it to call the normal version:
That way users can call it with you enum type and it will just work
清洁工?您正在做一些不干净的事情:获取强类型值并将其更改为另一种类型。您正在故意规避类型系统。当你做一些不干净的事情时,它应该看起来不干净。
唯一“更干净”的方法是使用 C 型演员阵容。我不确定这是否“更干净”。
Cleaner? You're doing something unclean: taking a strongly-typed value and changing it to another type. You're deliberately circumventing the type system. When you do something unclean, it should look unclean.
The only "cleaner" way to do it is with a C-style cast. And I'm not sure that this is "cleaner".