Skip to content

Instantly share code, notes, and snippets.

@ned14
Created February 3, 2016 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ned14/9ef2a9d00da0ffc877b8 to your computer and use it in GitHub Desktop.
Save ned14/9ef2a9d00da0ffc877b8 to your computer and use it in GitHub Desktop.
AFIO v1 style of C++ bitfields
#include <stdio.h>
#define BOOST_AFIO_DECLARE_CLASS_ENUM_AS_BITFIELD(type) \
inline constexpr type operator&(type a, type b) \
{ \
return static_cast<type>(static_cast<size_t>(a) & static_cast<size_t>(b)); \
} \
inline constexpr type operator&=(type a, type b) \
{ \
return static_cast<type>(static_cast<size_t>(a) & static_cast<size_t>(b)); \
} \
inline constexpr type operator|(type a, type b) \
{ \
return static_cast<type>(static_cast<size_t>(a) | static_cast<size_t>(b)); \
} \
inline constexpr type operator|=(type a, type b) \
{ \
return static_cast<type>(static_cast<size_t>(a) | static_cast<size_t>(b)); \
} \
inline constexpr type operator~(type a) \
{ \
return static_cast<type>(~static_cast<size_t>(a)); \
} \
inline constexpr bool operator!(type a) \
{ \
return 0==static_cast<size_t>(a); \
}
enum class flag : size_t
{
none=0,
delete_on_close=1,
disable_safety_fsyncs=2
};
BOOST_AFIO_DECLARE_CLASS_ENUM_AS_BITFIELD(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);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment