应该如何ç位标志枚举翻译成C ++? [英] How should C bitflag enumerations be translated into C++?

查看:144
本文介绍了应该如何ç位标志枚举翻译成C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++是大多数是C的超集,但并非总是如此。特别是,而在C和C枚举值++隐式转换成int,则反之则不然:只在C做整数转换回枚举值。因此,通过枚举声明定义bitflags无法正常工作。因此,这是在C OK,但不是在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;
}

应该如何这一问题得到有效和正确处理,最好在不损害使用美孚作为变量类型的调试友好性(它分解成在手表等组件bitflags)?

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.

澄清:我正在翻译一大(> 300K)C程序到C ++,所以我正在寻找在两个运行时和开发人员时间高效的翻译。只需插入管型在所有适当的位置可能需要几个星期。

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.

推荐答案

为什么不直接把结果返回到一个Foo?

Why not just cast the result back to a Foo?

Foo x = Foo(Foo_First | Foo_Second);

编辑:我不明白你的问题的范围,当我第一次回答了这个问题。以上将做几个点的修复工作。对于你想做什么,你需要定义一个|操作员需要2美孚参数,并返回富:

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:

Foo operator|(Foo a, Foo b)
{
    return Foo(int(a) | int(b));
}

的int类型转换在那里prevent不需要的递归。

The int casts are there to prevent undesired recursion.

这篇关于应该如何ç位标志枚举翻译成C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆