MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / main

Function main

Examples/Modules/Chapter 19/Ex19_08/Ex19_08.cpp:9–33  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7bool less(int x, int y) { return x < y; }
8
9int main()
10{
11 int a{ 18 }, b{ 8 };
12 std::cout << std::boolalpha; // Print true/false rather than 1/0
13
14 std::function<bool(int,int)> compare;
15
16 compare = less; // Store a function pointer into compare
17 std::cout << a << " < " << b << ": " << compare(a, b) << std::endl;
18
19 compare = std::greater<>{}; // Store a function object into compare
20 std::cout << a << " > " << b << ": " << compare(a, b) << std::endl;
21
22 int n{ 10 }; // Store a lambda closure into compare
23 compare = [n](int x, int y) { return std::abs(x - n) < std::abs(y - n); };
24 std::cout << a << " nearer to " << n << " than " << b << ": " << compare(a, b);
25
26 // Check whether a function<> object is tied to an actual function
27 std::function<void(const int&)> empty;
28 if (empty) // Or, equivalently: 'if (empty != nullptr)'
29 {
30 std::cout << "Calling a default-constructed std::function<>?" << std::endl;
31 empty(a);
32 }
33}

Callers

nothing calls this directly

Calls 1

compareFunction · 0.50

Tested by

no test coverage detected