C++14 Features
Generic lambdas, variable templates
Interview Relevant: C++14 improvements
C++14 Features
C++14 was a smaller update, mainly focusing on fixing and improving C++11 features.
Key Improvements
- Generic Lambdas: Use
autoin lambda parameters. - Return Type Deduction: Functions can deduce return types automatically.
- make_unique: Helper for creating unique_ptr (missing in C++11).
- Binary Literals:
0b1010. - Digit Separators:
1'000'000for readability.
Code Examples
C++14 improvements and new features.
cpp
1// Generic lambdas
2auto print = [](auto x) { cout << x << endl; };
3print(42);
4print("hello");
5
6// Lambda capture initializers
7int x = 10;
8auto lambda = [y = x + 1]() { return y; };
9
10// Return type deduction
11auto add(int a, int b) {
12 return a + b; // Compiler deduces int
13}
14
15// Variable templates
16template<typename T>
17constexpr T pi = T(3.14159265359);
18
19double d = pi<double>;
20float f = pi<float>;
21
22// Binary literals
23int binary = 0b1010; // 10
24
25// Digit separators
26int million = 1'000'000;
27
28// make_unique
29auto ptr = make_unique<int>(42);
30
31// [[deprecated]] attribute
32[[deprecated("Use newFunc instead")]]
33void oldFunc() { }
34
35// Relaxed constexpr
36constexpr int factorial(int n) {
37 int result = 1;
38 for (int i = 2; i <= n; i++) {
39 result *= i; // Loops allowed in C++14!
40 }
41 return result;
42}