Using C flag enums in C++

前端 未结 5 507
时光说笑
时光说笑 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条回答
  •  Happy的楠姐
    2020-12-16 16:39

    C++ has stricter rules than C regarding enums. You'll need to cast the value to the enumeration type when calling:

    do_something((CEnumType)(C_ENUM_VALUE_APPLE | C_ENUM_VALUE_BANANA));
    

    Alternatively, you can writer a wrapper function that takes an int to do the cast for you, if you want to avoid writing the cast every time you call it:

    void do_something_wrapper(int types)
    {
        do_something((CEnumType)types);
    }
    ...
    do_something_wrapper(C_ENUM_VALUE_APPLE | C_ENUM_VALUE_BANANA);
    

    Though I don't know if I want to see what you get when you cross an apple with a banana...

提交回复
热议问题