Skip to content

Instantly share code, notes, and snippets.

@ned14
Created Feb 4, 2016
Embed
What would you like to do?
Improved enum bitfield thanks to feedback from Boost dev list
#include <stdio.h>
#include <type_traits>
#define BOOST_CXX14_CONSTEXPR constexpr
template<class Enum> struct bitfield : public Enum
{
using enum_type = typename Enum::enum_type;
using underlying_type = std::underlying_type_t<enum_type>;
private:
underlying_type _value;
public:
//! Default construct to all bits zero
constexpr bitfield() : _value(0) { }
//! Implicit construction from the C style enum
constexpr bitfield(enum_type v) : _value(v) { }
//! Explicit construction from the underlying type of the C enum
explicit constexpr bitfield(underlying_type v) : _value(v) { }
//! Permit explicit casting to the underlying type
explicit constexpr operator underlying_type() const { return _value; }
//! Test for non-zeroness
explicit constexpr operator bool() const { return !!_value; }
//! Test for zeroness
constexpr bool operator !() const { return !_value; }
//! Performs a bitwise NOT
constexpr bitfield operator ~() const noexcept { return bitfield(~_value); }
//! Performs a bitwise AND
constexpr bitfield operator &(bitfield o) const noexcept { return bitfield(_value&o._value); }
//! Performs a bitwise AND
BOOST_CXX14_CONSTEXPR bitfield &operator &=(bitfield o) noexcept { _value &= o._value; return *this; }
//! Performs a bitwise OR
constexpr bitfield operator |(bitfield o) const noexcept { return bitfield(_value | o._value); }
//! Performs a bitwise OR
BOOST_CXX14_CONSTEXPR bitfield &operator |=(bitfield o) noexcept { _value |= o._value; return *this; }
//! Performs a bitwise XOR
constexpr bitfield operator ^(bitfield o) const noexcept { return bitfield(_value ^ o._value); }
//! Performs a bitwise XOR
BOOST_CXX14_CONSTEXPR bitfield &operator ^=(bitfield o) noexcept { _value ^= o._value; return *this; }
};
#define BOOST_AFIO_BITFIELD_BEGIN(type) \
struct type##_base \
{ \
enum enum_type
#define BOOST_AFIO_BITFIELD_END(type) \
;}; \
using type = bitfield<type##_base>;
BOOST_AFIO_BITFIELD_BEGIN(flag)
{
none=0,
delete_on_close=1,
disable_safety_fsyncs=2
}
BOOST_AFIO_BITFIELD_END(flag)
int main(void)
{
flag f(flag::disable_safety_fsyncs);
flag f2(f&flag::none);
f2|=flag::delete_on_close;
constexpr flag f3(flag::disable_safety_fsyncs);
constexpr flag f4(f3&flag::none);
printf("f=%d, f2=%d, f3=%d, f4=%d\n", (unsigned) f, (unsigned) f2, (unsigned) f3, (unsigned) f4);
if(f)
printf("f is null\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment