C++11 standard conformant bitmasks using enum class

后端 未结 5 1255
春和景丽
春和景丽 2021-01-31 03:17

Can you implement standard conformant (as described in 17.5.2.1.3 of the n3242 draft) type safe bitmasks using enum class? The way I read it, a type T is a bitmask if it support

5条回答
  •  無奈伤痛
    2021-01-31 04:01

    A short example of enum-flags below.

    #indlude "enum_flags.h"
    
    ENUM_FLAGS(foo_t)
    enum class foo_t
        {
         none           = 0x00
        ,a              = 0x01
        ,b              = 0x02
        };
    
    ENUM_FLAGS(foo2_t)
    enum class foo2_t
        {
         none           = 0x00
        ,d              = 0x01
        ,e              = 0x02
        };  
    
    int _tmain(int argc, _TCHAR* argv[])
        {
        if(flags(foo_t::a & foo_t::b)) {};
        // if(flags(foo2_t::d & foo_t::b)) {};  // Type safety test - won't compile if uncomment
        };
    

    ENUM_FLAGS(T) is a macro, defined in enum_flags.h (less then 100 lines, free to use with no restrictions).

提交回复
热议问题