taming-cpp

Experiments with C++ and comparisons with C
git clone https://git.tronto.net/taming-cpp
Download | Log | Files | Refs | README

commit d0f3f64bb42ea8194c20f0eadd35821cab346143
parent 873ae98050baf54a9a17ac54896de732134206af
Author: Sebastiano Tronto <sebastiano@tronto.net>
Date:   Fri, 17 Jan 2025 07:52:02 +0100

Started work on templates article

Diffstat:
MREADME.md | 9+++++++++
Atemplates/pair.cpp | 35+++++++++++++++++++++++++++++++++++
Atemplates/swap.cpp | 16++++++++++++++++
3 files changed, 60 insertions(+), 0 deletions(-)

diff --git 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 @@ -0,0 +1,35 @@ +#include <iostream> + +template <typename S, typename T> +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<int, char> 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 @@ -0,0 +1,16 @@ +#include <iostream> + +template<typename S, typename T> +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; +}