Why is boost::dynamic_bitset a template?

561 Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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).