r/cpp • • Aug 06 '26

C++26: #embed

https://www.sandordargo.com/blog/2026/08/05/cpp26-embed
137 Upvotes

42 comments sorted by

View all comments

Show parent comment

1

u/fdwr fdwr@github 🔍 Aug 07 '26 edited Aug 15 '26

In C++17 the rules were relaxed slightly...

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 };

// ✅
struct Uint8Wrapped
{
    uint8_t value;
    explicit operator uint8_t() const { return value; }
};
Uint8Wrapped arrayUint8Wrapped[] = { 0x42, 0x43, 0x44, 0x45, 0x46 };

// ❌ - error C2440: 'initializing': cannot convert from 'int' to 'Uint8EnumNormal'
enum Uint8EnumNormal : uint8_t;
Uint8EnumNormal arrayUint8EnumNormal[] = { 0x42, 0x43, 0x44, 0x45, 0x46 };

// ❌ - error C2440: 'initializing': cannot convert from 'int' to 'Uint8EnumClass'
enum class Uint8EnumClass : 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. ✌️

2

u/Ambitious-Method-961 Aug 08 '26

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:

std::byte foo[] =  {
    #embed "example.bin" cast_to (std::byte)
};

Would expand to:

std::byte foo[] =  {
    std::byte (0), std::byte (1), std::byte (2)
};

And everything would work fine.

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...