There isn't much you can do to avoid the if
unless you absolutely know that the optional has a value (and if you know, why use an optional?)
You could wrap the conditional part into a lambda/function:
#include <optional>
#include <boost/container/flat_set.hpp>
std::optional<boost::container::flat_set<int> > objects;
void f(int _v)
{
auto assure = [&]() -> decltype(auto)
{
if (objects.has_value())
return *objects;
else
return objects.emplace();
};
assure().insert(_v);
}
another way...
#include <optional>
#include <boost/container/flat_set.hpp>
std::optional<boost::container::flat_set<int> > objects;
template<class T>
auto assure_contents(std::optional<T>& opt) -> T&
{
if (opt.has_value())
return *opt;
else
return opt.emplace();
}
void f(int _v)
{
assure_contents(objects).insert(_v);
}