Non-uniform byte initialization

117 Views Asked by At

Is there a reason, simple enough to explain to non language lawyers, why the initializations commented out fail to compile while the first one succeeds?

#include <cstddef>

void test() {
  std::byte a{42};
  //std::byte b = {42};
  //std::byte c[]{48, 49};
}

Code on https://godbolt.org/z/nGfzjnh4f


The error is:

error: cannot initialize a variable of type 'std::byte' with an rvalue of type 'int'
1

There are 1 best solutions below

2
On BEST ANSWER

Because std::byte is an enum class and std::byte b = {42} is not direct-list-initialization which is the only syntax allowed here since it uses C++17's relaxed enum class initialization rules:

An enumeration can be initialized from an integer without a cast, using list initialization, if all of the following are true:

  • The initialization is direct-list-initialization.
  • The initializer list has only a single element.
  • The enumeration is either scoped or unscoped with underlying type fixed.
  • The conversion is non-narrowing.

(emphasis mine)

And since std::byte b = {42} doesn't satisfy the first bullet requirement, we get the mentioned error.