juce::Optional<> ->get();

Would is be possible to add a get() method to JUCE’s optional class similar to std::optional?

In our case it could return a sensible default & throw an assert in debug?

In my code all classes pull from a single optional which is processed once per block but available across a wide range of nodes & processors across many different files. – In the base I handled the cases of a certain type not being set – and if it doesn’t exist I set it in the optional.

This means that I am sure the value is set in the optional – yet I still need to use the funky *info->getBpm() syntax or info->getBpm().orFallback(x) – I prefer the latter as the first is confusing – but it’s annoying to have so many .orFallback() all over the place.

I’d prefer not to add this feature.

The stdlib implementation of optional::value returns a reference to the contained object, so there’s no way to return a sensible default if the optional is not engaged. Changing the signature to return by value would be a departure from the stdlib API which could complicate migration from juce::Optional to std::optional in the future. Adding a completely new/separate member function would similarly complicate such a migration.

We could take the same approach as the std version, and throw an exception on failure (perhaps we could add an assertion before the throw, too), but I don’t really want to encourage throwing exceptions in JUCE. Exceptions aren’t appropriate in realtime contexts, and they’re difficult to use/test correctly even in non-performance-critical contexts.

I’d suggest implementing the functionality that you’re after as a non-member function. This approach can easily be tweaked to work with std::optional too:

template <typename Value>
Value get (juce::Optional<Value> opt, Value fallback = {})
    if (opt.hasValue())
        return *opt;

    return fallback;

Love it! Thanks for the suggestion @reuk