//******************************************************** // The following code example is taken from the book // C++23 - The Complete Guide // by Nicolai M. Josuttis (www.josuttis.com) // http://www.cppstd23.com // // The code is licensed under a // Creative Commons Attribution 4.0 International License // http://creativecommons.org/licenses/by/4.0/ //******************************************************** #include #include #include template std::ostream& operator<< (std::ostream& strm, const std::optional& opt) { if (opt) { return strm << *opt; } else { return strm << ""; } } std::optional asOptInt(const std::string& s) // returns int or "no value" { try { return std::stoi(s); } catch (...) { return {}; } } int main() { using OptString = std::optional; 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{"fallback data"}; }) .and_then(asOptInt) .or_else([]{ std::cout << "there is no int\n"; return std::optional{42}; }); std::cout << " => " << opt << "\n\n"; } }