I want to have a bitset constexpr variable in my program. bitset can have unsigned long long value as a constructor which is 64bit value, I need 100 bit value. As per this Q&A, we can use constructor that takes a string as an argument and initialize it that way, but it won't be constexpr value. Is there any possible way?
-
Literal strings and the pointers to them are compile-time constants (which is why they can be used as non-type template arguments). – Some programmer dude Apr 12 '21 at 12:11
-
@Someprogrammerdude Is that relevant to the question? – super Apr 12 '21 at 12:18
2 Answers
the constructor std::bitset<N>(uint64_t)
is the only useful constexpr
callable constructor here:
constexpr bitset(unsigned long long _Val) noexcept : _Array{static_cast<_Ty>(_Need_mask ? _Val & _Mask : _Val)} {}
and that will only provide 64 bits of information.
But since it is possible to initalize a std::bitset
at compile time with another std::bitset
, in theory you could make a constexpr
function that initializes a std::bitset
and returns that, like this:
template<size_t N>
constexpr std::bitset<N> make_bitset(const char* x) {
std::bitset<N> result;
for (int i = 0; x && x[i] != '\0'; ++i) {
result.set(i, x[i] - '0');
}
return result;
}
sadly this doesn't compile as std::bitset<N>::set
is not declared constexpr
. But looking at the set
function, in theory this function could be declared constexpr
:
bitset& _Set_unchecked(size_t _Pos, bool _Val) noexcept { // set bit at _Pos to _Val, no checking
auto& _Selected_word = _Array[_Pos / _Bitsperword];
const auto _Bit = _Ty{1} << _Pos % _Bitsperword;
if (_Val) {
_Selected_word |= _Bit;
} else {
_Selected_word &= ~_Bit;
}
return *this;
}
but until then, you can't initialize a std::bitset
with more than 64 bits of information at compile time.

- 7,754
- 2
- 26
- 55
-
`std::bitset` really is a disappointment when you look what it could be. – Quirin F. Schroll Mar 18 '22 at 13:44
Unfortunately, constexpr
std::bitset
's constructors are limited to
- default one,
- and the one taking
unsigned long long
.
In addition, its mutators (set
, operator[]
, ...) are not constexpr
neither, so you cannot create a constexpr
"factory".
You have to create your own bitset (or use one from another library).

- 203,559
- 14
- 181
- 302