The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <iostream>
#include <string>
#include <optional>
template<typename ValT>
std::ostream& operator<< (std::ostream& strm, const std::optional<ValT>& opt)
{
if (opt) {
return strm << *opt;
}
else {
return strm << "<novalue>";
}
}
std::optional<int> asOptInt(const std::string& s) // returns int or "no value"
{
try {
return std::stoi(s);
}
catch (...) {
return {};
}
}
int main()
{
using OptString = std::optional<std::string>;
for (auto myOpt : {OptString{"42"}, OptString{"data"}, OptString{std::nullopt}}) {
std::cout << "myOpt: " << myOpt << '\n';
auto opt = myOpt.or_else([]{
std::cout << "there is no string\n";
return std::optional<std::string>{"fallback data"};
})
.and_then(asOptInt)
.or_else([]{
std::cout << "there is no int\n";
return std::optional<int>{42};
});
std::cout << " => " << opt << "\n\n";
}
}