C++17 Features
Structured bindings, if constexpr
Interview Relevant: C++17 enhancements
C++17 Features
C++17 introduced significant features for clearer and more robust code.
Key Features
- Structured Bindings: Unpack tuples/structs:
auto [x, y] = point;. - std::optional: Represent optional values safely.
- std::string_view: Lightweight, non-owning string reference.
- if constexpr: Compile-time branching for templates.
- Filesystem API: Standardized file operations (
std::filesystem).
Code Examples
C++17 features for modern C++ development.
cpp
1// Structured bindings
2auto [x, y] = make_pair(1, 2);
3for (auto& [key, value] : myMap) { }
4
5// if with initializer
6if (auto it = map.find(key); it != map.end()) {
7 cout << it->second;
8}
9
10// if constexpr (compile-time if)
11template<typename T>
12auto getValue(T t) {
13 if constexpr (is_pointer_v<T>) {
14 return *t;
15 } else {
16 return t;
17 }
18}
19
20// Fold expressions
21template<typename... Args>
22auto sum(Args... args) {
23 return (args + ...); // Fold over +
24}
25
26// Inline variables
27inline int globalVar = 42;
28
29// std::optional
30optional<int> findValue();
31if (auto opt = findValue(); opt) {
32 cout << *opt;
33}
34
35// std::variant
36variant<int, double, string> v = 42;
37
38// std::string_view
39void process(string_view sv) { }
40
41// Nested namespace definition
42namespace A::B::C { }
43
44// [[nodiscard]] attribute
45[[nodiscard]] int compute() { return 42; }
46
47// Filesystem library
48namespace fs = std::filesystem;