Last active
January 10, 2023 00:59
-
-
Save copyrat90/c5cce5a80daa02ab8e38289ca6428160 to your computer and use it in GitHub Desktop.
enum_as_flags.hpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef COPYRAT90_ENUM_AS_FLAGS_HPP | |
#define COPYRAT90_ENUM_AS_FLAGS_HPP | |
#include <type_traits> | |
#define ENUM_AS_FLAGS(Enum) \ | |
static_assert(std::is_enum<Enum>::value, "Template argument for Enum is not an enum."); \ | |
\ | |
constexpr bool operator!(Enum a) { \ | |
using Int = typename std::underlying_type<Enum>::type; \ | |
return !static_cast<Int>(a); \ | |
} \ | |
\ | |
constexpr Enum operator~(Enum a) { \ | |
using Int = typename std::underlying_type<Enum>::type; \ | |
return static_cast<Enum>(~static_cast<Int>(a)); \ | |
} \ | |
\ | |
constexpr Enum operator|(Enum a, Enum b) { \ | |
using Int = typename std::underlying_type<Enum>::type; \ | |
return static_cast<Enum>(static_cast<Int>(a) | static_cast<Int>(b)); \ | |
} \ | |
\ | |
constexpr Enum& operator|=(Enum& a, Enum b) { \ | |
return a = a | b; \ | |
} \ | |
\ | |
constexpr Enum operator&(Enum a, Enum b) { \ | |
using Int = typename std::underlying_type<Enum>::type; \ | |
return static_cast<Enum>(static_cast<Int>(a) & static_cast<Int>(b)); \ | |
} \ | |
\ | |
constexpr Enum& operator&=(Enum& a, Enum b) { \ | |
return a = a & b; \ | |
} \ | |
\ | |
constexpr Enum operator^(Enum a, Enum b) { \ | |
using Int = typename std::underlying_type<Enum>::type; \ | |
return static_cast<Enum>(static_cast<Int>(a) ^ static_cast<Int>(b)); \ | |
} \ | |
\ | |
constexpr Enum& operator^=(Enum& a, Enum b) { \ | |
return a = a ^ b; \ | |
} | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "enum_as_flags.hpp" | |
enum class MyFlags { | |
NONE = 0, | |
A = 1 << 0, | |
B = 1 << 1, | |
C = 1 << 2, | |
D = 1 << 3, | |
ALL = A | B | C | D | |
}; | |
ENUM_AS_FLAGS(MyFlags); | |
int main() { | |
constexpr MyFlags f = MyFlags::A | MyFlags::B; | |
// Check if `f` has `MyFlags::A` in it | |
static_assert(!!(f & MyFlags::A)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment