From d0f3f64bb42ea8194c20f0eadd35821cab346143 Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Fri, 17 Jan 2025 07:52:02 +0100 Subject: Started work on templates article --- README.md | 9 +++++++++ templates/pair.cpp | 35 +++++++++++++++++++++++++++++++++++ templates/swap.cpp | 16 ++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 templates/pair.cpp create mode 100644 templates/swap.cpp diff --git a/README.md b/README.md index 41825cc..46a15bf 100644 --- a/README.md +++ b/README.md @@ -27,3 +27,12 @@ For the [second post in the series](https://sebastiano.tronto.net/blog/2024-12-26-taming-cpp-raii/). Various small examples on constructors, destructors and related things. + +## Templates + +For the +[third post](https://sebastiano.tronto.net/blog/2025-01-TODO) + +Various examples on templates, constraints and concepts. + +See also [zmodn](https://git.tronto.net/zmodn). 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 @@ +#include + +template +class Pair { +public: + S first; + T second; + + Pair(S s, T t) : first{s}, second{t} {} + + void print() const { + std::cout << "(" << first << ", " << second << ")"; + } +}; + +int main() { + Pair p(42, 'x'); + p.second = 'y'; + + std::cout << "p ="; + p.print(); + std::cout << std::endl; + + Pair q(1.23, 7); // template argument deduction + + std::cout << "q ="; + q.print(); + std::cout << std::endl; + + std::cout << "int type name: " << typeid(7).name() << std::endl; + std::cout << "char type name: " << typeid('x').name() << std::endl; + std::cout << "double type name: " << typeid(1.23).name() << std::endl; + std::cout << "Type of p: " << typeid(p).name() << std::endl; + std::cout << "Type of q: " << typeid(q).name() << std::endl; +} 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 @@ +#include + +template +void swap(S& a, T& b) { + S tmp = a; + a = b; + b = tmp; +} + +int main() { + int x = 3; + std::string y = "1.0"; + swap(x, y); + std::cout << "x: " << x << std::endl; + std::cout << "y: " << y << std::endl; +} -- cgit v1.3