-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambdas-templated-cpp20.cpp
More file actions
69 lines (52 loc) · 2.16 KB
/
lambdas-templated-cpp20.cpp
File metadata and controls
69 lines (52 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#pragma clang diagnostic ignored "-Wunused-variable"
#pragma clang diagnostic ignored "-Wunused-value"
#define CATCH_CONFIG_MAIN // Tells Catch2 to provide a main()
#include "../catch/catch_amalgamated.hpp"
#include "utils.h"
using namespace std;
// templated lambdas
// - Templated lambdas let you write generic lambdas with "explicit template
// parameters" instead of relying on auto, giving you access to the actual
// type.
// - Syntax: []<typename T>(T x) { } — T is explicit, not deduced via auto
// like generic lambdas: auto twice = [](auto x) { return x * 2; };
//
// Key notes:
// - Solves the main auto weakness: you can name, constrain, and decompose
// the type
// - Can enforce two params are same type — auto can't do this
// - Works with concepts for constrained templates: []<std::integral T>
// - Can take variadic template params: []<typename... Ts>
// - Prefer over auto params when you need the type name inside the body
TEST_CASE("tem-lam-1") {
//// 1. main usage
// before
// C++14 generic lambda — auto hides the type
auto print_ = [](auto x) {
// what IS x? can't use sizeof(x), can't get value_type
std::cout << x << "\n";
};
// now
// C++20 — explicit template parameter
auto print = []<typename T>(T x) {
cout << x << ": " << sizeof(T) << "\n";
};
print(42); // T = int, sizeof = 4
print(3.14); // T = double, sizeof = 8
print("hi"); // T = char*, sizeof = 8
//// 2. enforce constraints with concepts
auto multiply = []<std::integral T>(T a, T b) {
return a * b;
};
multiply(3, 4); // ✓ int
// multiply(3.0, 4.0); // ❌ compile error — not integral
//// 3. enforce same type for multiple params
// C++14 — auto allows different types silently
auto add14 = [](auto a, auto b) { return a + b; };
add14(1, 2.5); // !! BAD, silently mixes int + double
// C++20 — T enforces both are same type
auto add20 = []<typename T>(T a, T b) { return a + b; };
add20(1, 2); // ✓ both int
// add20(1, 2.5); // ❌ compile error — type mismatch
// REQUIRE(maxConnections == 128);
}