简体   繁体   English

为什么 std::bitset 只采用 constexpr 值?

[英]Why does std::bitset only takes constexpr value?

I want to decide size of bitset during runtime.我想在运行时决定位集的大小。
But std::bitset<N> only accepts constexpr values for N, not even const values.但是std::bitset<N>只接受 N 的 constexpr 值,甚至不接受 const 值。
Which means size of bitset must be decided before compiling.这意味着必须在编译之前确定位集的大小。

I know std::vector provides optimization for bool array,我知道std::vector为 bool 数组提供优化,
but it lacks those useful bitset members I need.但它缺少我需要的那些有用的 bitset 成员。

Question 1: Why does N has to be constexpr value?问题 1:为什么 N 必须是 constexpr 值?
Well I'm guessing that's because bitset is template, but still, this is massive inconvenience.好吧,我猜那是因为 bitset 是模板,但这仍然带来很大的不便。
Bitset could have been a class rather than a template. Bitset可能是一个类而不是模板。
It's constructor can take size_t as argument, than I can create variable length bitset.它的构造函数可以将 size_t 作为参数,而不是我可以创建可变长度的位集。
The same question goes for std::array .同样的问题也适用于std::array
Could've been std::array<type> foo(size, values) .可能是std::array<type> foo(size, values)

Question 2: Is there any 'Hacks' that lets me create variable-length bitset?问题 2:是否有任何“黑客”可以让我创建可变长度的位集?
I'm pretty sure there won't be any, considering how template works.考虑到模板的工作原理,我很确定不会有。
But just maybe, there is some clever trick :)但也许,有一些聪明的技巧:)
If not, I'll have to use std::vector<bool> and implement bitset members myself.如果没有,我将不得不使用std::vector<bool>并自己实现 bitset 成员。

Why does N has to be constexpr value?为什么 N 必须是 constexpr 值?

You are right.你是对的。 Size of both std::bitset and std::array is specified as a template parameter, so it cannot be set during runtime. std::bitsetstd::array大小都指定为模板参数,因此不能在运行时设置。

However, in the past there were some proposals for introducing dynamic arrays in the C++ standard.但是,过去有一些建议在 C++ 标准中引入动态数组。 One of them was called std::dynarray .其中之一被称为std::dynarray Eventually, it won't be introduced into standard but you can see here a more elaborative description of its lifetime.最终,它不会被引入到标准中,但您可以在这里看到对其生命周期的更详细的描述。

Is there any 'Hacks' that lets me create variable-length bitset?是否有任何“黑客”可以让我创建可变长度的位集?

If you have access to the Boost library, you can use its dynamic_bitset .如果您有权访问 Boost 库,则可以使用它的dynamic_bitset

Bitset could have been a class rather than a template. Bitset 可能是一个类而不是模板。

It is made for a purpose and if that is not yours, you simply have to use something different.它是有目的的,如果那不是你的,你只需要使用不同的东西。

If you want to store single bits, which means you like to store bool with variable size, you simply can use std::vector< bool >如果您想存储单个位,这意味着您喜欢存储可变大小的bool ,您只需使用std::vector< bool >

If not, I'll have to use std::vector and implement bitset members myself.如果没有,我将不得不使用 std::vector 并自己实现 bitset 成员。

A bitset is a container of bits.位集是位的容器。 So what do you mean by implementing bitset yourself?那么你自己实现 bitset 是什么意思?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM