導入
最後に、C++17 で加わった「あると便利」な機能を2つ紹介します。「値があるか無いか」を安全に表す std::optional と、pair や tuple をきれいに分解する「構造化束縛」です。実務のモダン C++ で頻繁に見かけます。
説明
std::optional<T> は「T の値があるか、無いか」を表します。「見つからなかった」を -1 や特別な値で表す代わりに、意図を型で明示できます。値の有無は if (opt)、取り出しは *opt や opt.value() です。
#include <iostream>
#include <optional>
#include <string>
using namespace std;
// 見つからないことがある検索
optional<int> findAge(const string& name) {
if (name == "たろう") return 20;
return nullopt; // 見つからない → 値なし
}
int main() {
auto a = findAge("たろう");
if (a) { // 値があるか
cout << "年齢: " << *a << endl; // 20
}
auto b = findAge("だれか");
cout << b.value_or(-1) << endl; // -1(無ければ既定値)
return 0;
}
「構造化束縛」は、pair・tuple・struct を一度に複数の変数へ分解する記法です。auto [x, y] = ... と書きます。第14章の map を回すときにも登場しました。
flowchart LR
p["pair<string, int> { 名前, 年齢 }"]
p -->|"auto [name, age] = p;"| a["name ← 名前<br/>age ← 年齢"]
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> scores = { {"たろう", 80}, {"はな", 95} };
for (const auto& [name, score] : scores) { // 一度に分解
cout << name << ": " << score << endl;
}
// たろう: 80 / はな: 95
return 0;
}
まとめ
std::optional<T> は「値があるか無いか」を型で安全に表し、value_or で既定値も扱えます。構造化束縛 auto [a, b] = ... は pair/tuple/struct をきれいに分解します。どちらも、意図が明確で読みやすいモダン C++ を書くための機能です。