0 day streak
cpp / intermediate
Snippet

Functional Result Containers for Null-Free Interfaces

The std::optional class template manages an optional contained value, which might or might not be present. It is an excellent alternative to returning magic values (like -1) or null pointers, leading to clearer and safer control flows.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <optional>
#include <string>
std::optional<int> try_parse(const std::string& s) {
try {
return std::stoi(s);
} catch (...) {
return std::nullopt;
}
}
void usage() {
auto result = try_parse("123");
if (result.has_value()) {
int value = *result;
}
}
Breakdown
1
std::optional<int> try_parse(...)
Returns a container that may or may not hold an integer.
2
return std::nullopt;
Explicitly indicates that no value is being returned.