Boost logo

Boost :

Subject: [boost] Improved typesafe bitfield (was: Re: How best to implement a bitfield in C++ 14?)
From: Niall Douglas (s_sourceforge_at_[hidden])
Date: 2016-02-04 10:19:19


Firstly I'd like to thank Vicente and Tongari for their ideas as
without their feedback I wouldn't have come up with
https://gist.github.com/ned14/614d8f3cca25924964ea which combines
ideas from all three of us.

I'm relatively happy with this solution. Declaration is as follows:

BOOST_AFIO_BITFIELD_BEGIN(flag)
{
  none=0,
  delete_on_close=1,
  disable_safety_fsyncs=2
}
BOOST_AFIO_BITFIELD_END(flag)

Example usage:

  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);
  if(f) ...

This solution is convenient for programmers to use, works as you'd
expect from a bitfield, if(bf) works and is 100% constexpr and
generates zero runtime overhead, and it's ODR-used correct. The
tradeoff is unfortunately now individual flag::XXX are not typesafe
and have implicit convertibility to int, though 'flag' itself and any
output of any operation on 'flag' is typesafe. Also, there is an ugly
macro begin and end of the declaration, but I think this is the best
typesafe bitfield I can think of which has a syntax resembling C
bitfields.

Any comments absolutely welcome.

Niall

-- 
ned Productions Limited Consulting
http://www.nedproductions.biz/ 
http://ie.linkedin.com/in/nialldouglas/



Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk