C++11 standard conformant bitmasks using enum class

后端 未结 5 1128
春和景丽
春和景丽 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:14

    I'm not entirely sure what your acceptance criteria are, but you can just make operator & return a wrapper class with appropriate conversions and an explicit operator bool:

    #include 
    
    template using Underlying = typename std::underlying_type::type;
    template constexpr Underlying
    underlying(T t) { return Underlying(t); }
    
    template struct TruthValue {
        T t;
        constexpr TruthValue(T t): t(t) { }
        constexpr operator T() const { return t; }
        constexpr explicit operator bool() const { return underlying(t); }
    };
    
    enum class Color { RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff };
    constexpr TruthValue
    operator&(Color l, Color r) { return Color(underlying(l) & underlying(r)); }
    

    All your other operators can continue to return Color, of course:

    constexpr Color
    operator|(Color l, Color r) { return Color(underlying(l) | underlying(r)); }
    constexpr Color operator~(Color c) { return Color(~underlying(c)); }
    
    int main() {
        constexpr Color YELLOW = Color::RED | Color::GREEN;
        constexpr Color WHITE = Color::RED | Color::GREEN | Color::BLUE;
        static_assert(YELLOW == (WHITE & ~Color::BLUE), "color subtraction");
        return (YELLOW & Color::BLUE) ? 1 : 0;
    }
    

提交回复
热议问题