include <optional> int main() { std::optional<int> o{13}; // if init return 13 return o.value_or(2); // else return 2 }
#include <string> #include <iostream> #include <optional> std::optional<std::string> create(bool b) { if (b) return "Godzilla"; return {}; } auto create2(bool b) { return b ? std::optional<std::string>{"Godzilla"} : std::nullopt; } int main() { std::cout << "create(false) returned" << create(false).value_or("empty") << '\n'; if (auto str = create2(true)) { std::cout << "create2(true) returned " << *str << '\n'; } }
create(false) returned empty create2(true) returned Godzilla
The #1 tech hiring platform