Boost logo

Boost :

Subject: [boost] Is there any interest in type-safe container of bool flags with noexcept guarantees?
From: Роман Орлов (compmaniak_at_[hidden])
Date: 2017-03-21 16:31:47

Hello Boost community,
I'd like to determine interest in this kind of container.
For managing sets of bool flags developers often use std::bitset or c-like
manual bit manipulations. Each approach brings problems.
Some disadvantages of using std::bitset:
* unpredictable and greedy allocation of bit storage;
* setters/getters can throw exceptions;
* it operates in low-level terms like "a bit number";
* we can easily assign one instance of std::bitset to another with the same
number of bits but semantically they may differ.
Instead of managing bits via numbers let's manage them via types.
So start by declaring some types
class eats_meat;
class eats_grass;
class has_tail;
Then bind these types to flag identifiers
typedef typed_flags<eats_meat, eats_grass, has_tail> animal;

Unlike std::bitset the 'animal' instance allocates a minimal possible storage
(in this case sizeof(animal) == 1).
Create flags from scratch
animal wolf;
wolf.set<eats_meat, has_tail>();
wolf.set(flag<has_tail>{1}, flag<eats_meat>{1});
Create flags with a flexible human-readable constructor
wolf = animal{flag<has_tail>{1}, flag<eats_meat>{1}, flag<eats_grass>{0}};

I have implemented a minimal working prototype in my github repo
If you're interested you can try it online here
Expected benefits
* delegating calculation of a bit position for a certain type to compiler
gives us a strong type safety and prevents typos;
* noexcept guarantee of setting and getting bit values;
* we shouldn't take care of bits because we work in terms of typed properties;
* great readability, taking a short glance on a type definition tells you what
this type is about.

Some people on reddit ( found this library useful.
Any thoughts on the idea of the container would be much appreciated. --

Boost list run by bdawes at, gregod at, cpdaniel at, john at