Modern C++ › C++17
Structured Bindings and std::optional
Unpack pairs, tuples and structs in one line, and represent "maybe a value" without sentinel values.
Since C++17 intermediate #structured-bindings#optional#vocabulary-types
Explanation
Structured bindings declare several names bound to the elements of a pair, tuple, array, or plain struct. std::optional<T> holds either a T or nothing, replacing magic return values like -1 or nullptr.
Example
#include <iostream>
#include <map>
#include <optional>
#include <string>
std::optional<int> findAge(const std::map<std::string, int>& m, const std::string& name) {
auto it = m.find(name);
if (it == m.end()) return std::nullopt;
return it->second;
}
int main() {
std::map<std::string, int> ages = {{"Ann", 30}, {"Bob", 25}};
for (const auto& [name, age] : ages) // structured bindings
std::cout << name << " is " << age << '\n';
if (auto a = findAge(ages, "Ann")) // if-with-initializer style check
std::cout << "Ann: " << *a << '\n';
std::cout << findAge(ages, "Zed").value_or(-1) << '\n';
}
Pitfalls
*opton an empty optional is undefined behavior;opt.value()throwsstd::bad_optional_access.- Structured bindings are names for the members, not copies, when you write
auto&. - You cannot capture a structured binding in a lambda in C++17 (allowed from C++20).
Legacy vs modern
C++98 needed it->first / it->second or std::pair + .first, and used bool find(..., int& out) output parameters for “maybe” results.
Exercises
1. Rewrite std::pair<int,int> p = f(); int a = p.first, b = p.second;
auto [a, b] = f();