Search code examples
c++c++17constexprstd-bitset

Why std::bitset<5>{}[0] is not a constexpr?


std::bitset has constexpr constructor and constexpr operator[] so the following code compiles successfully:

#include <bitset>

typedef std::bitset<5> BitSet;

constexpr BitSet s1;
static_assert(!s1[0]);

buy why the following code does not?

static_assert(BitSet{}[0]);

Solution

  • When you write BitSet{} a temporary object is created whose type is BitSet. But std::bitset's operator[] for non-const objects is not constexpr!

    In your first example s1 is implicitly const, so it uses the const operator[] which is constexpr.

    Since you cannot const qualify a temporary directly (like const Foo() is not valid), you can always just add const to your alias:

    using BitSet = const std::bitset<5>;