Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

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]);
like image 270
Alexey Starinsky Avatar asked Jan 02 '23 07:01

Alexey Starinsky


1 Answers

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>;
like image 79
Rakete1111 Avatar answered Jan 14 '23 09:01

Rakete1111