Defining the size of bitset using a template

喜欢而已 提交于 2019-12-08 06:49:41

问题


I have a class

template <class MAX> 
class A 
{
   std::bitset<MAX> _mem ; 
}

The aim of this class , is so that I can have variable length bitsets. To be used in different parts of my program.

But clang complete gives me the error

template argument for non type template parameter should be an expression

回答1:


The bitset template expects a constant integral expression, not a type. Try this:

template < size_t MAX >
class A { std::bitset<MAX> _mem; };



回答2:


It's not clear exactly what you want to accomplish here. When you say "variable length bitsets", you could mean a number of bitsets of different sizes, but the size of each one is constant. If that's the case, you're on the right track with std::bitset, but since the size of a std::bitset is an integer, you need to pass an integer of some sort:

template <size_t MAX>
class A {
    std::bitset<MAX> _mem;
};

If you mean you want bitsets that can actually vary in size (i.e., an individual bitset might be one size at one time, and anther size at a different time, then you might want to consider something like Boost dynamic_bitset instead of reinventing this particular wheel.

Another possibility would be std::vector<bool>. This gets quite a bit of bad press (including quite a few people recommending against ever using it). It is different from vectors of other types, but it can still be useful as long as you understand what you're really dealing with.

One place to be especially careful is with writing generic algorithms that might deal with a vector<T> for any type T. In this case, it's fairly common that vector<bool> will require special treatment.



来源:https://stackoverflow.com/questions/33762440/defining-the-size-of-bitset-using-a-template

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