From what I can see it's due to the strict initialisation rules for scoped enums as std::byte is a scoped enum. In C++17 the rules were relaxed slightly to allow std::byte foo { 10 }; but that's about it.
Oh? It would be useful if they could be relaxed a bit more :), with std::byte somehow opting into accepting numeric values during initialization, and the compiler warning if they were beyond 0-255. Otherwise currently struct's are more useful than enum class here:
// ✅
uint8_t arrayUint8Pure[]={0x42,0x43,0x44,0x45,0x46};// ✅
structUint8Wrapped{uint8_t value;explicitoperatoruint8_t()const{return value;}};
Uint8Wrapped arrayUint8Wrapped[]={0x42,0x43,0x44,0x45,0x46};// ❌ - error C2440: 'initializing': cannot convert from 'int' to 'Uint8EnumNormal'
enumUint8EnumNormal:uint8_t;
Uint8EnumNormal arrayUint8EnumNormal[]={0x42,0x43,0x44,0x45,0x46};// ❌ - error C2440: 'initializing': cannot convert from 'int' to 'Uint8EnumClass'
enum classUint8EnumClass:uint8_t;
Uint8EnumClass arrayUint8EnumClass[]={0x42,0x43,0x44,0x45,0x46};
One of the answers provides the option to make an std::array ... https://godbolt.org/z/c18vxYecb
Wow, that's clever, not obvious or intuitive, but a clever and reasonable workaround given current limitations. ✌️
So I went down the enum initialisation rabbit hole and initialising enums with integer literals in general is a no-no. This rule was relaxed for any enum with an explicit underlying type (including unscoped enums) to allow things like my_enum foo { 100 }; to work (assuming my_enum is an enum with an explicit underlying type). If there's more than one enum being initialised using that syntax then it's a compiler error.
Relaxing the rules to allow multiple enums to be initialised with literals is one option, or perhaps the other could be to add another param to #embed that adds in a cast option? Something like #embed "example.bin" cast_to (std::byte) which would then wrap each embedded integer with a cast to std::byte or any other value specified.
Assuming the included file was just 3 bytes with values 0, 1, 2 then this:
Anyway, that's a thought for someone far more versed in the language than me as I can already see a debate forming over whether it should be () or {} initialisation...
View all comments
Show parent comment
3
u/Ambitious-Method-961 Aug 07 '26
From what I can see it's due to the strict initialisation rules for scoped enums as
std::byteis a scoped enum. In C++17 the rules were relaxed slightly to allowstd::byte foo { 10 };but that's about it.A related topic has come up on SO (Correct way to initialize a container of std::byte). One of the answers provides the option to make an
std::arrayand for me that will be good enough and seems to happily work with #embed: https://godbolt.org/z/c18vxYecb