Compressed std::expected

127 Views Asked by At

std::expected is a discriminated union introduced in C++23 that can be seen as a generalization of std::optional in that it stores an error value when std::optional would be empty.

Now, I figure that a lot of types already have unused storage when they are invalid or empty. A simple example would be std::span, which stores a pointer and a size. If the pointer is null, the size has no function and could hold an error value instead.

This would in theory offer the opportunity to optimize the memory consumption of a std::expected<std::span>, because there would be no need to store the discriminator (typically a bool) separately. One could use the pointer as a discriminator instead.

I am sure there are many standard and user types that would provide this opportunity when combined with std::expected.

This could presumably be exploited with partial template specializations for std::expected. If done right, it could be transparent to a user. The memory savings would be automatic, for all types that satisfy the criterium of having an existing member that can serve as the discriminator.

Now my question: Has the standard library been designed with this optimization in mind, and are there implementations that make use of this possibility? What standard types would lend themselves to this kind of optimization? Are existing standard library implementations already exploiting this opportunity?

0

There are 0 best solutions below