CPP Modern C++ Features (C++17/20) 2 — Questions and Answers
Question 1: What does the C++17 structured binding `auto [x, y] = std::make_pair(1, 2.0);` deduce for `x` and `y`?
- x is int, y is double (Correct answer)
- x is double, y is int
- Both are double
- Both are int
Correct answer: x is int, y is double
Structured bindings decompose the pair preserving each element's original type, so x is int and y is double.
Question 2: Which C++17 feature allows `if (auto it = map.find(key); it != map.end())` syntax?
- If statement with initializer (Correct answer)
- Structured bindings
- Constexpr if
- Fold expressions
Correct answer: If statement with initializer
C++17 added an optional init-statement to if and switch, scoping the declared variable to the conditional block.
Question 3: What is the result of the fold expression `(args + ...)` when args is an empty pack?
- Compilation error for operator+ (Correct answer)
- 0
- Undefined behavior
- An empty value
Correct answer: Compilation error for operator+
Unary fold over + with an empty pack is ill-formed; only &&, ||, and comma operator have identity elements defined for empty packs.
Question 4: What does `std::optional<int> opt;` evaluate to when used in a boolean context?
- false, because it holds no value (Correct answer)
- true, because the object exists
- Compilation error
- Undefined behavior
Correct answer: false, because it holds no value
A default-constructed std::optional is disengaged, and its bool conversion returns false.
Question 5: Which C++17 class template deduction guide allows `std::vector v = {1, 2, 3};` without specifying `<int>`?
- Class Template Argument Deduction (CTAD) (Correct answer)
- Template parameter packs
- Concepts
- Variadic templates
Correct answer: Class Template Argument Deduction (CTAD)
CTAD lets the compiler deduce template arguments from constructor call arguments, eliminating the need for explicit angle-bracket types.
Question 6: What guarantee does C++17 provide about the evaluation of `f() + g()` regarding the order of `f` and `g`?
- No guaranteed order between f() and g() (Correct answer)
- f() is always evaluated before g()
- g() is always evaluated before f()
- They are evaluated simultaneously
Correct answer: No guaranteed order between f() and g()
C++17 strengthened sequencing rules but still leaves the relative order of operand evaluation for + unspecified.
Question 7: In C++17, `if constexpr (condition)` differs from regular `if` in that:
- The discarded branch is not instantiated in templates (Correct answer)
- It evaluates at runtime only
- It can only be used with integral types
- Both branches are always compiled
Correct answer: The discarded branch is not instantiated in templates
if constexpr discards the non-taken branch at compile time within templates, preventing instantiation of otherwise ill-formed code.
What does the C++17 structured binding `auto [x, y] = std::make_pair(1, 2.0);` deduce for `x` and `y`?