3

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?

Taher Kawantwala
  • 115
  • 2
  • 5
  • 13

2 Answers2

3

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.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
2

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302