Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Non-uniform byte initialization

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Because std::byte is an enum class and std::byte b = {42} is not direct-list-initialization which uses C++17’s relaxed enum class initialization rules and only allow for direct list initialization.

This can be seen from 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading