C++ Logo

std-proposals

Advanced search

std::optional<T>::try_emplace

From: Ryan P. Nicholl <rnicholl_at_[hidden]>
Date: Mon, 14 Jun 2021 22:26:25 +0000
I would like to suggest "try_emplace" for std::optional,

which works like the following:

template <typename T, typename ... Ts>
void std::optional<T>::try_emplace(Ts && .. ts)
{
try
{
emplace(std::forward<Ts>(ts)...);
}
catch (...)
{}
}

Main use case is optional components which we want to eat exceptions if they fail to initialize:

std::optional<logger> m_logger;

...

m_logger.try_emplace(logs_directory);
...
if (m_logger.has_value())
{
m_logger->log(message);
}
else
{
std::cerr << message << std::endl;
}

--
Ryan P. Nicholl
Tel: (678)-358-7765

Received on 2021-06-14 17:27:15