I'm trying to get a bitmask from a bitfield struct, at compile time. One of the tricks that I tried, which looks promising to me, is using std::bit_cast
, because it is supposed to be constexpr.
My test code can be found here: https://godbolt.org/z/er48M63sh
This is the source:
#include <bit>
struct Bitfield {
int :3;
int x:3;
};
constexpr int mask() noexcept {
Bitfield bf{};
bf.x -= 1;
return std::bit_cast<int>(bf);
}
int test() {
int mask1 = mask();
// constinit static int mask2 = mask(); // Why doesn't this compile?
return 0;
}
As you can see, it doesn't actually calculate the bitmask at compile time, but at runtime, so for some reason the constexpr trick isn't working. I fail to see why, however, since cppreference doesn't seem to list my case as one that defeats constexpr in std::bit_cast
.
Does anybody see what's wrong? Does this thing have a chance of working?