One-line call to std::optional::emplace only if it has no value
In the same spirit than the creation of an instance in a std::map when calling operator[] , I would like to emplace (direclty in the expression) in an std::optional only if has_value() is false. In other words, I would like to one-line this code :
std::vector>>> data;
//...
if(condition)
{
if(!data[42].has_value()) data[42].emplace();
data[42].value()[3].push_back("foo");
}
Something like :
if(condition)
data[42].value_or_emplace()[3].push_back("foo");
I know I can create my own tool like this :
template
T& value_or_emplace(std::optional& o)
{
return (o.has_value() ? o.value() : o.emplace());
}
if(condition)
value_or_emplace(data[42])[3].push_back("foo");
But I expect something I missed in the standard library.