forked from hsf-training/cpluspluscourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctors.tex
48 lines (46 loc) · 1.44 KB
/
functors.tex
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
\subsection[()]{Function objects}
\begin{frame}[fragile]
\frametitlecpp[98]{Function objects}
\begin{block}{Concept}
\begin{itemize}
\item also known as functors (no relation to functors in math)
\item a class that implements \cppinline{operator()}
\item allows to use objects in place of functions
\item with constructors and data members
\end{itemize}
\end{block}
\begin{cppcode}
struct Adder {
int m_increment;
Adder(int increment) : m_increment(increment) {}
int operator()(int a) { return a + m_increment; }
};
Adder inc1{1}, inc10{10};
int i = 3;
int j = inc1(i); // 4
int k = inc10(i); // 13
int l = Adder{25}(i); // 28
\end{cppcode}
\end{frame}
\begin{frame}[fragile]
\frametitlecpp[20]{Function objects}
\begin{exampleblockGB}{Function objects as function arguments}{https://godbolt.org/z/zxqYG6xzT}{function objects}
\begin{cppcode}
int count_if(const auto& range, auto predicate) {
int count = 0; // ↑ template (later)
for (const auto& e : range)
if (predicate(e)) count++;
return count;
}
struct IsBetween {
int lower, upper;
bool operator()(int value) const {
return lower < value && value < upper;
}
};
int arr[]{1, 2, 3, 4, 5, 6, 7};
std::cout << count_if(arr, IsBetween{2, 6}); // 3
// prefer: std::ranges::count_if
\end{cppcode}
\end{exampleblockGB}
\end{frame}