⚡C++AdvancedLesson 48 of 50CamboFreelanceJune 19, 2026
C++17 Features
Explore C++17 features: structured bindings, std::optional, if initializers, std::filesystem, and if constexpr.
Advanced10 min readLesson 48 of 50
Key C++17 Features
C++17 added powerful features that make code cleaner and more expressive. Compile with -std=c++17.
Structured Bindings
#include <iostream>
#include <map>
#include <tuple>
using namespace std;
int main() {
// Decompose pair
map<string,int> scores = {{"Alice",95},{"Bob",82}};
for (auto& [name, score] : scores) {
cout << name << ": " << score << endl;
}
// Decompose tuple
auto [x, y, z] = make_tuple(1, 2.5, "hello");
cout << x << " " << y << " " << z << endl;
return 0;
}
std::optional
Represents a value that may or may not be present — safer than returning -1 or null:
#include <optional>
optional<int> divide(int a, int b) {
if (b == 0) return nullopt;
return a / b;
}
auto result = divide(10, 2);
if (result.has_value())
cout << "Result: " << *result << endl; // 5
auto bad = divide(5, 0);
cout << bad.value_or(-1) << endl; // -1
if with Initializer
map<string,int> m = {{"key", 42}};
if (auto it = m.find("key"); it != m.end()) {
cout << "Found: " << it->second << endl;
}
// 'it' not visible outside the if