Search⌘ K

Examples Of std::optional

Explore practical examples of using std optional in C++17 to manage nullable values and enhance code safety. Understand how optional fields like nicknames and ages can be implemented, how to parse command-line integers with error avoidance, and other common uses such as optional configurations and geometric computations. This lesson helps you grasp real-world applications of std optional to write cleaner and more robust C++ code.

Here are a few more extended examples where std::optional fits nicely.

User Name with an Optional Nickname and Age

C++ 17
#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.

Parsing ints From The

...