I have read about std::optional<std::reference_wrapper<T>> as a way to pass around optional references.
However, I'm unable to think of a practical example where I'd do that, instead of just using an optional<T>&.
For example, suppose I'm writing a function which needs to take an optional vector<int> by reference.
I could do this:
void f(optional<reference_wrapper<vector<int>>> v) {
// ...
}
int main() {
vector<int> v = {1, 2, 3, 4};
f(make_optional<reference_wrapper<vector<int>>>(std::ref(v));
return 0;
}
But why not just do this?
void f(optional<vector<int>>& v) {
// ...
}
int main() {
f(make_optional<vector<int>>>(std::initializer_list{1, 2, 3, 4}));
return 0;
}
Please give an example where optional<reference_wrapper<T>> is preferable to optional<T>&. The semantic differences, and especially the ways they can be leveraged in practice aren't clear to me.