Something went wrong. Try again.
Bitmask operations for `enum class` in C++.
Something went wrong. Try again.
1.4 kB · 56 lines · Created 1w ago
C++
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#pragma once
#include <utility>
#define BITANY(value, bits) (((value) & (bits)) != 0)#define BITALL(value, bits) (((value) & (bits)) == (bits))#define BITMSK(value, mask, bits) (((value) & (mask)) == (bits))#define BITGET(value, n) (((value) & (1 << (n))) >> (n))#define BITSET(value, n, b) ((b) ? ((value) |= (1<<(n))) : (value &= ~(1<<(n))))
template<typename T>concept BitmaskTypeLike =std::is_enum_v<T> && requires { std::underlying_type_t<T>{}; };
template<BitmaskTypeLike T>constexpr T operator|(T lhs, T rhs) noexcept{ return static_cast<T>(std::to_underlying(lhs) | std::to_underlying(rhs));}
template<BitmaskTypeLike T>constexpr T operator&(T lhs, T rhs) noexcept{ return static_cast<T>(std::to_underlying(lhs) & std::to_underlying(rhs));}
template<BitmaskTypeLike T>constexpr T operator^(T lhs, T rhs) noexcept{ return static_cast<T>(std::to_underlying(lhs) ^ std::to_underlying(rhs));}
template<BitmaskTypeLike T>constexpr T operator~(T e) noexcept{ return static_cast<T>(~std::to_underlying(e));}
template<BitmaskTypeLike T>constexpr T& operator|=(T& lhs, T rhs) noexcept{ return lhs = lhs | rhs;}
template<BitmaskTypeLike T>constexpr T& operator&=(T& lhs, T rhs) noexcept{ return lhs = lhs & rhs;}
template<BitmaskTypeLike T>constexpr T& operator^=(T& lhs, T rhs) noexcept{ return lhs = lhs ^ rhs;}
https://open-std.org/jtc1/sc22/wg21/docs/papers/2026/p4313r1.html