4
votes

To define a bitset with 16 bits, it will be like:

std::bitset<16> bs(0x123);

If let me design a bitset class, I will probably make it like this:

mine::bitset bs(16, 0x123);

Is there any reason that std::bitset is implemented by template?

Is this a good pattern that we should apply in some situations?

1
One is a static bitset, the other would be dynamic. If you already know the desired size, why shouldn't you take advantage of this knowledge? - Kerrek SB
In other words: When you decide to shop and feed your family, would you rather go and buy the required amount, or would you, every day, wait at home until everyone is at home, count them, lock them up in a mutex, go shopping for the computed quantity of family members, and then cook? That's more flexible if you randomly create and lose children. - Kerrek SB

1 Answers

4
votes

Is there any reason that std::bitset is implemented by template? Is this a good pattern that we should apply in some situations?

Because std::bitset is designed to be a static bitset. In some cases, the compile-time size, will be very helpful, especially to the compiler, to optimize your program. If you want a dynamic bitset you can use boost::dynamic_bitset. Just like there is std::array and std::vector, there's always a place for statically sized containers and dynamically sized containers.