I have a method that returns an optional struct, like this:
auto getBook(const std::string &title) const -> std::optional<Book>;
I want to call this method in another method that returns the optional author. Problem is that the implementation should always check whether the optional returned by getBook is filled in before a method can be called, like this:
auto getAuthor(const std::string &title) const -> std::optional<Author>
{
const auto optBook = getBook(title);
if (optBook.has_value)
return optBook->getAuthor();
else
return std::nullopt;
}
Is there a way to write this in a shorter way, so that if the optional is filled the method is called, but if the optional is empty, std::nullopt
is returned. Something like this (I know this currently doesn't work but you get my point):
auto getAuthor(const std::string &title) const -> std::optional<Author>
{
return getBook(title).getAuthor();
}