2 ms·
Right, c++ has no builtin discriminated union, and std::optional<T&> is actually not valid in C++ (unfortunately). But discriminant-less custom optionals class
by gpderetta 5y ago
Right, c++ has no builtin discriminated union, and std::optional<T&> is actually not valid in C++ (unfortunately).
But discriminant-less custom optionals classes with 'zero' type support via traits are easy to do (and I have done it many times). You do not have to rely on the compiler identifying a safe empty state and you can define any application specific one. For example if for one specific
(and common) use case strings are always non null, optional<string, non_null_trait> has an obvious implementation.
So, yes, these sorts of optimizations are not done by the compiler has it has no notion of discriminated types (one day maybe...), but can be done generically by the programmer. In fact you could in principle optimize multiple layers of variant<optional<...>,... > and collapse everything in one discriminant,as long as you do not provide reference access to the sub variants; the required metaprogram is not going to be pretty though.
One of the advantages of C++ is that it allows this sort of control.
- cogman10 5y ago> One of the advantages of C++ is that it allows this sort of control. But I believe what the OP showed is that Rust also allows you to have that level of control. However, the default behavior for rust is to do the optimization that you have to go out of your way to manually implement in C++. Rust isn't taking away control from what you can do in C++, instead, it's made the idiomatic approach one that is well optimized by the compiler.