在C使用C标志++枚举 [英] Using C flag enums in C++

查看:80
本文介绍了在C使用C标志++枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C API定义像这样的枚举:

I have a C API that defines an enum like so:

typedef enum
{
  C_ENUM_VALUE_NONE    = 0,
  C_ENUM_VALUE_APPLE   = (1 << 0),
  C_ENUM_VALUE_BANANA  = (1 << 1),
  C_ENUM_VALUE_COCONUT = (1 << 2),
  // etc.
  C_ENUM_VALUE_ANY     = ~0
} CEnumType;

有是使用枚举,定义为方法

There is a method that uses the enum, defined as:

void do_something(CEnumType types);

在C,你可以调用是这样的:

In C, you can call something like:

do_something(C_ENUM_VALUE_APPLE | C_ENUM_VALUE_BANANA);

然而,如果你尝试调用这种方式在C ++(Linux操作系统,G ++编译器),你会得到一个错误,的从'诠释'到'CEnumType

什么是使用C API从我的C ++应用程序的正确方法是什么?

推荐答案

您需要转换 INT s到在C ++枚举,但你可以隐藏在自定义投运营商:

You need to cast ints to enums in C++, but you can hide the cast in a custom OR operator:

CEnumType operator|(CEnumType lhs, CEnumType rhs) {
    return (CEnumType) ((int)lhs| (int)rhs);
}

通过这个操作符的地方,你可以写你的原始

With this operator in place, you can write your original

do_something(C_ENUM_VALUE_APPLE | C_ENUM_VALUE_BANANA);

和它将编译和运行没有问题。

and it will compile and run without a problem.

这篇关于在C使用C标志++枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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