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?
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.