4 ms·
> C++ references cannot be optional by design; that is one of the aspects of pointers that C++ references "fix", and you cannot code around it. You keep repeat
by kllrnohj 5y ago
> C++ references cannot be optional by design; that is one of the aspects of pointers that C++ references "fix", and you cannot code around it.
You keep repeating this as if it's at all relevant. The single purpose of std::optional is to make things optional that cannot themselves be optional by design. That C++ references cannot be optional are exactly why it's a perfect fit for std::optional.
You seem to be talking about the difficulty in storing T& if the value isn't present. That's not actually hard to do, that's what std::reference_wrapper does already. The C++ standard library already solved that, and trivially so.
Rather the issue is a difference in assignment behavior, as the Boost.Optional discusses: https://www.boost.org/doc/libs/1_69_0/libs/optional/doc/html/boost_optional/rebinding_semantics_for_assignment_of_optional_references.html https://www.boost.org/doc/libs/1_69_0/libs/optional/doc/html... (and Boost.Optional does allow T&, because optional<T&> is well-formed & well-defined)
> reference_wrapper doesn't actually have anything to do with references
What? Literally from the documentation:
"std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references."
The only thing it does is take a T& and return a T&. That it stores it internally as a T* is an implementation detail.
As for your example snippet, you just have a bug in usage since you didn't read reference_wrappers docs. It needs to be `swap(rx.get(), ry.get());` since the _wrapper part of its name is actually significant, you have to get the wrapped value out of it. Alternatively `swap((int&) rx, (int&) ry);` would also have worked.