aboutsummaryrefslogtreecommitdiff
path: root/templates
diff options
context:
space:
mode:
authorSebastiano Tronto <sebastiano@tronto.net>2025-01-17 07:52:02 +0100
committerSebastiano Tronto <sebastiano@tronto.net>2025-01-17 07:52:02 +0100
commitd0f3f64bb42ea8194c20f0eadd35821cab346143 (patch)
tree84355ea4008769382a8300aa11b2b43fd9dd86c1 /templates
parent873ae98050baf54a9a17ac54896de732134206af (diff)
downloadtaming-cpp-d0f3f64bb42ea8194c20f0eadd35821cab346143.tar.gz
taming-cpp-d0f3f64bb42ea8194c20f0eadd35821cab346143.zip
Started work on templates article
Diffstat (limited to 'templates')
-rw-r--r--templates/pair.cpp35
-rw-r--r--templates/swap.cpp16
2 files changed, 51 insertions, 0 deletions
diff --git a/templates/pair.cpp b/templates/pair.cpp
new file mode 100644
index 0000000..42b97c9
--- /dev/null
+++ b/templates/pair.cpp
@@ -0,0 +1,35 @@
1#include <iostream>
2
3template <typename S, typename T>
4class Pair {
5public:
6 S first;
7 T second;
8
9 Pair(S s, T t) : first{s}, second{t} {}
10
11 void print() const {
12 std::cout << "(" << first << ", " << second << ")";
13 }
14};
15
16int main() {
17 Pair<int, char> p(42, 'x');
18 p.second = 'y';
19
20 std::cout << "p =";
21 p.print();
22 std::cout << std::endl;
23
24 Pair q(1.23, 7); // template argument deduction
25
26 std::cout << "q =";
27 q.print();
28 std::cout << std::endl;
29
30 std::cout << "int type name: " << typeid(7).name() << std::endl;
31 std::cout << "char type name: " << typeid('x').name() << std::endl;
32 std::cout << "double type name: " << typeid(1.23).name() << std::endl;
33 std::cout << "Type of p: " << typeid(p).name() << std::endl;
34 std::cout << "Type of q: " << typeid(q).name() << std::endl;
35}
diff --git a/templates/swap.cpp b/templates/swap.cpp
new file mode 100644
index 0000000..94e231e
--- /dev/null
+++ b/templates/swap.cpp
@@ -0,0 +1,16 @@
1#include <iostream>
2
3template<typename S, typename T>
4void swap(S& a, T& b) {
5 S tmp = a;
6 a = b;
7 b = tmp;
8}
9
10int main() {
11 int x = 3;
12 std::string y = "1.0";
13 swap(x, y);
14 std::cout << "x: " << x << std::endl;
15 std::cout << "y: " << y << std::endl;
16}

Generated with cgit - Back to sebastiano.tronto.net