-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric-lambda-cpp14.cpp
More file actions
47 lines (33 loc) · 1.18 KB
/
generic-lambda-cpp14.cpp
File metadata and controls
47 lines (33 loc) · 1.18 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
#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;
namespace {
// generic lambdas
// - auto in a lambda parameter is syntactic sugar for a template —
// - the compiler generates a templated operator() equivalent to
// template<typename T> auto operator()(T x).
//
// auto f = [](auto x) { return x * 2; };
//
// Key notes:
// - auto a, auto b — two "independent" types;
// (use <typename T>(T a, T b) to enforce same types)
//// 1. A generic lambda
auto twice = [](auto x) { return x * 2; };
// De-sugared equivalent
struct __lambda {
template<typename T>
auto operator()(T x) const { return x * 2; }
};
auto print = [](auto x) { std::cout << x << "\n"; };
// print(42); // operator()(int)
// print(3.14); // operator()(double)
// print("hello"); // operator()(const char*)
//// 2. C++20 — same type enforced
auto add20 = []<typename T>(T a, T b) { return a + b; };
// add20(1, 2); // ✓
// add20(1, 2.5); // ❌ — both must be same type T
}