Access the underlying std::optional of juce::Optional

At the moment juce::Optional wraps a private std::optional instance. Since we make a lot of use of std::optional in our code base there are now situations where I need to convert a returned juce::Optional value to its std::optional equivalent.

The comment on the juce::Optional class tells me

In new code, you should probably prefer using std::optional directly.

This is intended to stand-in for std::optional while JUCE's minimum
supported language standard is lower than C++17. When the minimum language
standard moves to C++17, this class will probably be deprecated, in much
the same way that juce::ScopedPointer was deprecated in favour of
std::unique_ptr after C++11.

Given that C++17 has become the minimum standard for JUCE in the meantime and the class actually wraps a std::optional I think this outdated. To make the transition that is announced here smooth, it would be extremely helpful if juce::Optional had implicit conversion operators like e.g.

operator std::optional<Value>() &&            { return std::move (opt); }
operator const std::optional<Value>& () const { return opt; }

This would make it easy to pass the return values of JUCE calls returning an optional to functions expecting a std::optional and would probably not even break user code if JUCE decided to deprecate the class and let the functions return std::optional.

Even better would be

namespace juce {
using Optional=std::optional;

Let’s write new code :slight_smile:

1 Like

Not sure if I preferred this, given that the interface of std::optional is different from juce::Optional, e.g. std::optional::value_or is wrapped behind juce::Optional::orFallback. So with that approach the interface of juce::Optional would change in a breaking way – in that case I’d prefer a hard removal of juce::Optional from the interface over the type alias which hides this replacement a bit better – just like it was done with juce::ScopedPointer back then

Well ok, the juce::Optional could stay as deprecated. But I would like to see the occurences in juce to be replaced with std::optional, so I can choose not to use juce::Optional.

1 Like