Define bitset size at initialization?

久未见 提交于 2019-11-26 11:24:12

Boost has a dynamic_bitset you can use.

Alternatively, you can use a vector<bool>, which (unfortunately) is specialized to act as a bitset. This causes a lot of confusion, and in general is considered a bad idea. But that's how it works, so if that's what you need, you might as well use it, I suppose.

You should check out boosts dynamic_bitset.

What you are saying at the beginning is not true. The "examples you found" did not look as you posted. It is impossible to use a non-constant value to parametrize a template. So, your first example is invalid. Only constant expressions can serve as non-type arguments for a template. I.e. the non-type argument has to be a compile-time constant.

Of looks like you want to create a bitset whose size is not a compile-time constant. In this case the bitset template is out of question. You need an implementation of run-time sized bitset. For example, you can use std::vector<bool> - in many (if not all) implementations this template is specialized to implement a packed array of boolean values, where each element occupies one bit (as opposed to an bool object).

bitset requires size as a template parameter, meaning the size has to be capable of being determined at compile-time. It cannot be based on a runtime condition, like user input.

For that, you should look into std::vector or boost::dynamic_bitset. std::vector is a specialized template instantiation that uses one bit per element. Unlike bitset, it can be dynamically sized.

You can make your class a template to make the std::bitset size undetermined until your class gets instantiated. You can do it like this:

#include <bitset>

template<int size>
class Test
{
public: 
    std::bitset<size> bitset;
    //...
}

Then to use your class you would have to do this:

int exampleSize = 42;
Test<exampleSize> name;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!