Examples Of std::optional
Shown here are some practical examples where std::optional is useful.
We'll cover the following...
Here are a few more extended examples where std::optional
fits nicely.
User Name with an Optional Nickname and Age
Press + to interact
#include <optional>#include <iostream>using namespace std;class UserRecord {public:UserRecord (string name, optional<string> nick, optional<int> age) : mName{move(name)}, mNick{move(nick)}, mAge{age}{}friend ostream& operator << (ostream& stream, const UserRecord& user);private:string mName;optional<string> mNick;optional<int> mAge;};ostream& operator << (ostream& os, const UserRecord& user) {os << user.mName; if (user.mNick)os << ' ' << *user.mNick; if (user.mAge)os << ' ' << "age of " << *user.mAge; return os;}int main() {UserRecord tim { "Tim", "SuperTim", 16 };UserRecord nano { "Nathan", nullopt, nullopt };cout << tim << '\n';cout << nano << '\n';}
The above example shows a simple class with optional fields. While the name is obligatory, the other attributes: “nickname” and “age” are optional.