C 位标志枚举应如何转换为 C++?
C++ 大部分是 C 的超集,但并非总是如此。 特别是,虽然 C 和 C++ 中的枚举值都隐式转换为 int,但反之则不然:只有在 C 中,int 才会转换回枚举值。 因此,通过枚举声明定义的位标志无法正常工作。 因此,这在 C 中是可以的,但在 C++ 中不行:
typedef enum Foo
{
Foo_First = 1<<0,
Foo_Second = 1<<1,
} Foo;
int main(void)
{
Foo x = Foo_First | Foo_Second; // error in C++
return 0;
}
如何有效且正确地处理这个问题,理想情况下不损害使用 Foo 作为变量类型的调试器友好性质(它分解为手表等中的组件位标志) ?
还要考虑可能有数百个这样的标志枚举,以及数千个使用点。 理想情况下,某种有效的运算符重载可以解决问题,但它确实应该是有效的; 我想到的应用程序是计算密集型的,并且以速度快而闻名。
澄清:我正在将一个大型(> 300K)C 程序翻译成C++,因此我正在寻找在运行时和开发人员时都有效的翻译。 简单地将石膏插入所有适当的位置可能需要数周时间。
C++ is mostly a superset of C, but not always. In particular, while enumeration values in both C and C++ implicitly convert into int, the reverse isn't true: only in C do ints convert back into enumeration values. Thus, bitflags defined via enumeration declarations don't work correctly. Hence, this is OK in C, but not in C++:
typedef enum Foo
{
Foo_First = 1<<0,
Foo_Second = 1<<1,
} Foo;
int main(void)
{
Foo x = Foo_First | Foo_Second; // error in C++
return 0;
}
How should this problem be handled efficiently and correctly, ideally without harming the debugger-friendly nature of using Foo as the variable type (it decomposes into the component bitflags in watches etc.)?
Consider also that there may be hundreds of such flag enumerations, and many thousands of use-points. Ideally some kind of efficient operator overloading would do the trick, but it really ought to be efficient; the application I have in mind is compute-bound and has a reputation of being fast.
Clarification: I'm translating a large (>300K) C program into C++, so I'm looking for an efficient translation in both run-time and developer-time. Simply inserting casts in all the appropriate locations could take weeks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
为什么不直接将结果返回给 Foo?
编辑:当我第一次回答这个问题时,我不明白你的问题的范围。 上述内容适用于进行一些现场修复。 对于您想做的事情,您需要定义一个 | 接受 2 个 Foo 参数并返回 Foo 的运算符:
int 强制转换是为了防止意外的递归。
Why not just cast the result back to a Foo?
EDIT: I didn't understand the scope of your problem when I first answered this question. The above will work for doing a few spot fixes. For what you want to do, you will need to define a | operator that takes 2 Foo arguments and returns a Foo:
The int casts are there to prevent undesired recursion.