#include <iostream>
#include <optional>
#include <string>
// *** before: ***
// "there is no value" was told by a magic number, by an extra bool
// beside the result, or by an out parameter the caller had to prepare
bool findAgeOld(const std::string& name, int& out) {
if (name == "Ann") { out = 31; return true; }
return false;
}
// *** in version C++17: ***
std::optional<int> findAge(const std::string& name) {
if (name == "Ann") return 31;
return std::nullopt; // the absence is part of the type
}
int main() {
int age = 0;
if (findAgeOld("Ann", age))
std::cout << age << "\n";
if (auto found = findAge("Ann"); found.has_value())
std::cout << *found << "\n";
std::cout << findAge("Bob").value_or(-1) << "\n";
std::optional<std::string> nickname;
std::cout << nickname.has_value() << "\n";
nickname = "shorty";
std::cout << nickname->size() << "\n";
}