The structured bindings, the std::optional and the std::variant are three C++17 features that solve the same family of problems. They express "a value that may be one of several things" and "a value that may not be there" inside the type system. Together they remove a large class of the sentinel values, the out-parameters and the awkward tuples from the ordinary code.
The previous lesson in this module covered "How Do Lambdas Capture and Express Behavior Inline?", and the next lesson in this module is about "What Can constexpr Compute Before the Program Runs?".
Structured bindings name the parts
A structured binding lets you destructure a pair, a tuple or a map entry into named variables.
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
std::tuple<int, std::string, double> reading() {
return {42, "oil", 91.5};
}
int main() {
auto [value, label, percentage] = reading();
std::cout << value << ' ' << label << ' ' << percentage << '\n';
std::pair<std::string, int> entry = {"coolant", 30};
auto& [name, count] = entry;
std::cout << name << '=' << count << '\n';
return 0;
}The output shows the tuple and the pair being unpacked into the readable names.
42 oil 91.5
coolant=30And there are three forms. The plain auto [a, b] copies, the auto& [a, b] binds the references, and the const auto& [a, b] binds the const references. The last is the one to reach for when you only need to read.
Structured bindings with maps
They work particularly well with a map, where the entry is a pair of a key and a value.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> weights = {
{"p-001", 4}, {"p-002", 30}, {"p-003", 12}
};
for (const auto& [id, weight] : weights) {
std::cout << id << '=' << weight << ' ';
}
std::cout << '\n';
auto it = weights.find("p-002");
if (it != weights.end()) {
const auto& [id, weight] = *it;
std::cout << "found " << id << " with " << weight << '\n';
}
return 0;
}The output shows both the whole map and a single found entry read clearly.
p-001=4 p-002=30 p-003=12
found p-002 with 30optional for a value that may not be there
The std::optional holds a value or nothing. It replaces the sentinel values that every codebase otherwise accumulates, such as minus one, zero, a null pointer and an empty string.
#include <iostream>
#include <optional>
#include <string>
std::optional<int> find_weight(const std::string& id) {
if (id == "p-002") {
return 30;
}
return std::nullopt;
}
int main() {
auto found = find_weight("p-002");
if (found.has_value()) {
std::cout << "weight: " << *found << '\n';
} else {
std::cout << "not found\n";
}
auto missing = find_weight("p-009");
std::cout << "missing has value: " << missing.has_value() << '\n';
std::cout << "value or default: " << missing.value_or(-1) << '\n';
return 0;
}The output shows the two cases and the fallback.
weight: 30
missing has value: 0
value or default: -1And the important difference from a sentinel is that the compiler forces you to check. With an int return value the caller cannot tell "the weight is zero" apart from "nothing was found". With an optional the two states are distinct in the type.
optional with references and arguments
An optional can hold a reference, which is useful for returning a reference to something that may not exist.
#include <iostream>
#include <map>
#include <optional>
#include <string>
int main() {
std::map<std::string, int> weights = {{"p-001", 4}};
std::optional<std::reference_wrapper<const int>> found = [&]() -> std::optional<std::reference_wrapper<const int>> {
auto it = weights.find("p-001");
if (it == weights.end()) {
return std::nullopt;
}
return std::ref(it->second);
}();
if (found.has_value()) {
std::cout << "weight: " << found->get() << '\n';
}
return 0;
}The output shows the reference being read through the optional.
weight: 4And this is more machinery than most of the code needs, which is why returning a pointer or a std::map::iterator is often the more readable choice for the "may not be there" case.
variant for a value of several types
The std::variant holds one value that is chosen from a fixed list of the types, and the alternative is part of the type.
#include <iostream>
#include <string>
#include <variant>
using Reading = std::variant<double, std::string, bool>;
std::string describe(const Reading& reading) {
if (std::holds_alternative<double>(reading)) {
return "numeric: " + std::to_string(std::get<double>(reading));
}
if (std::holds_alternative<std::string>(reading)) {
return "text: " + std::get<std::string>(reading);
}
return std::string("flag: ") + (std::get<bool>(reading) ? "true" : "false");
}
int main() {
std::cout << describe(42.5) << '\n';
std::cout << describe(std::string("unknown")) << '\n';
std::cout << describe(true) << '\n';
return 0;
}The output shows all three of the alternatives being handled.
numeric: 42.500000
text: unknown
flag: trueAnd a variant is the type-safe replacement for a union with a manual tag. The index of the alternative is tracked by the library, so the tag and the value can never disagree.
Choosing between them
the situation use
------------------------------------------- --------------------------------
you have a pair, a tuple or a map entry the structured bindings
and you want the readable names
the function may or may not produce a value std::optional
and a sentinel would be ambiguous
the value is genuinely one of several std::variant
types and the compiler should check
the "not there" case is naturally a a pointer
null pointer and the target is a class
the function always succeeds a plain value
Quick reference
- The structured bindings unpack a pair, a tuple or a map entry into the named variables.
- You use the
const auto& [name, value]to read a map without copying it. - The
std::optionalholds a value or nothing, and you check it withhas_value(). - The
value_or(default)supplies a fallback, and the asterisk reads the value. - The
std::variantholds one of several types, and you check it withstd::holds_alternativeand read it withstd::get. - Both the optional and the variant make the "may not be there" case a part of the type.
Try it yourself: write a function that looks up a parcel weight and returns a std::optional instead of a sentinel of minus one, and call it for a parcel that exists and for one that does not. Next, return a pair of the identifier and the weight from a lookup and unpack it with a structured binding. Finally, build a std::variant that can hold a weight, a "not measured" marker or a text note, and handle each of the alternatives.