2

I have used boost::dynamic_bitset before as boost::dynamic_bitset<>, without really thinking about why it is templated.

Though I can understand why std::bitset is templated (the template type is used to specify the size of the bitset), I have now encountered some code of the form boost::dynamic_bitset<unsigned char> and I can't figure out what's the point of the template type.

How is boost::dynamic_bitset<unsigned char> different from boost::dynamic_bitset<>? Should one be used over the other in any situation?

user2891462
  • 3,033
  • 2
  • 32
  • 60

1 Answers1

3

From the documentation:

template <typename Block, typename Allocator>
class dynamic_bitset { // ...

The most obvious advantage of dynamic_bitset being a template is that you can specify your own Allocator type. This can be useful for a plethora of reasons (performance, memory contiguity, debugging). dynamic_bitset does allocate through Allocator if its internal storage needs to grow to accommodate more bits.

Additionally, it allows you to specify a Block type, which is the underlying primitive used to represent a bunch of bits. You might want to change the block type depending on the platform you're on or depending on how much memory you're willing to use (e.g. a smaller Block type would result in less wasted memory if not all bits are significant).

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • So in this case, `unsigned char` means that it uses an array of `unsigned char`s internally to store the bits? But this shouldn't make any difference from the outside, apart from memory usage, right? – user2891462 Sep 26 '17 at 10:18
  • 3
    @user2891462: it's also useful for interoperability with existing buffers. See `boost::to_block_range` for an example. – Vittorio Romeo Sep 26 '17 at 10:39