Commit 5cfd8c22cf67c9941f2fc3f0cbbd363ed8fdbd3e
1 parent
f264a977
Added concepts example
Showing
2 changed files
with
49 additions
and
1 deletions
examples08/01-template/makefile
1 | -all: minimum swap1 swap2 bubblesort | 1 | +all: minimum minimum_concepts swap1 swap2 bubblesort |
2 | 2 | ||
3 | minimum: minimum.o | 3 | minimum: minimum.o |
4 | g++ -g -Wall -pedantic $^ -o $@ | 4 | g++ -g -Wall -pedantic $^ -o $@ |
@@ -6,6 +6,12 @@ minimum: minimum.o | @@ -6,6 +6,12 @@ minimum: minimum.o | ||
6 | minimum.o: minimum.cpp | 6 | minimum.o: minimum.cpp |
7 | g++ -g -c -Wall -pedantic $< -o $@ | 7 | g++ -g -c -Wall -pedantic $< -o $@ |
8 | 8 | ||
9 | +minimum_concepts: minimum_concepts.o | ||
10 | + g++ -g -Wall -pedantic $^ -o $@ | ||
11 | + | ||
12 | +minimum_concepts.o: minimum_concepts.cpp | ||
13 | + g++ -std=c++20 -g -c -Wall -pedantic $< -o $@ | ||
14 | + | ||
9 | swap1: swap1.o | 15 | swap1: swap1.o |
10 | g++ -g -Wall -pedantic $^ -o $@ | 16 | g++ -g -Wall -pedantic $^ -o $@ |
11 | 17 |
examples08/01-template/minimum_concepts.cpp
0 → 100644
1 | +#include <iostream> | ||
2 | +#include <string> | ||
3 | +#include <concepts> | ||
4 | + | ||
5 | +using namespace std; | ||
6 | + | ||
7 | +template <class T> | ||
8 | +concept LessComparable = requires(const T l, const T r, bool res) | ||
9 | +{ | ||
10 | + res = (l < r); | ||
11 | +}; | ||
12 | + | ||
13 | +template <class T> T minimum(T x, T y) requires std::constructible_from<T, const T&> && LessComparable<T> | ||
14 | +{ | ||
15 | + if (x < y) | ||
16 | + return x; | ||
17 | + else | ||
18 | + return y; | ||
19 | +} | ||
20 | + | ||
21 | +class NotComparable | ||
22 | +{ | ||
23 | +}; | ||
24 | + | ||
25 | +class NotCopyConstructible | ||
26 | +{ | ||
27 | + public: | ||
28 | + NotCopyConstructible(){}; | ||
29 | + NotCopyConstructible(const NotCopyConstructible&) = delete; | ||
30 | + friend bool operator<(NotCopyConstructible, NotCopyConstructible){return true;}; | ||
31 | +}; | ||
32 | + | ||
33 | +int main() | ||
34 | +{ | ||
35 | + int x = 50, y = 30; | ||
36 | + string a = "hello", b = "goodbye"; | ||
37 | + cout << "minimum for ints " << minimum(x, y) << endl; | ||
38 | + cout << "minimum for strings " << minimum(a, b) << endl; | ||
39 | +// minimum(NotComparable(), NotComparable()); | ||
40 | +// minimum(NotCopyConstructible(), NotCopyConstructible()); | ||
41 | + | ||
42 | +} |