How to use C++11 enum class for flags

后端 未结 5 1246
面向向阳花
面向向阳花 2020-12-06 17:52

Say I have such a class:

enum class Flags : char
{
    FLAG_1 = 1;
    FLAG_2 = 2;
    FLAG_3 = 4;
    FLAG_4 = 8;
};

Now can I have a vari

5条回答
  •  北海茫月
    2020-12-06 18:16

    It's maybe better to make use of std::underlying_type instead of hard-coding char type.

    Flags operator|(Flags lhs, Flags rhs) {
        return static_cast(
            static_cast::type>(lhs) |
            static_cast::type>(rhs)
        );
    }
    

    Now, you can change the underlying type of your enumeration without needing to update that type in every bitwise operator overload.

提交回复
热议问题