Reputation: 7737
I have a library defining method()
that returns type V*
and can return nullptr
. What's the best way to wrap that method to turn the value into a std::optional<V>
?
The naive way would be something like:
std::optional<V> maybe_value;
V* value = method();
if (value != nullptr) {
maybe_value = *value; // assuming the type is even copyable
}
But I was hoping there'd already be some STL function I could use to do this as a one-liner wrapper around method()
.
Upvotes: 1
Views: 2196
Reputation: 38708
There is no such function. Assignment of any value makes the optional containing a value. But you can provide your own
template <typename T>
std::optional<T*> optional_ptr(T* ptr) {
return ptr ? std::optional<T*>(ptr) : std::optional<T*>();
}
Upvotes: 1
Reputation: 385224
Your way looks basically fine to me, and is roughly what I'd do. You don't want a one-liner here as it would not be very clear. Ultimately you can create a function for it if you like.
One concern: be very careful with ownership semantics here. Who owns *value
? Can it be copied? Is that meaningful? Can you move it instead? Who frees the original object?
Always ask these questions when passed a pointer, even if it appeared that the pointer was only chosen in order to add nullability.
To be quite honest, although std::optional
is preferable in new code (or code you're refactoring), I'm not convinced that wrapping a function like this is worth the potential confusion, not to mention the cost of a copy (if, indeed, that is necessary).
Upvotes: 4