Using C flag enums in C++

前端 未结 5 518
时光说笑
时光说笑 2020-12-16 15:51

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          


        
5条回答
  •  长情又很酷
    2020-12-16 16:44

    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.

提交回复
热议问题