Hi,

For me the name tells "emplace if empty, do nothing otherwise". I think this would match try_emplace in other containers better.

But I don't think we need a member function for either behavior.

Cheers,
Lénárd


From: "Ryan P. Nicholl via Std-Proposals" <std-proposals@lists.isocpp.org>
Sent: June 14, 2021 11:26:25 PM GMT+01:00
To: std-proposals <std-proposals@lists.isocpp.org>
Cc: "Ryan P. Nicholl" <rnicholl@protonmail.com>
Subject: [std-proposals] std::optional<T>::try_emplace

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