diff options
| author | Sebastiano Tronto <sebastiano@tronto.net> | 2025-01-17 07:52:02 +0100 |
|---|---|---|
| committer | Sebastiano Tronto <sebastiano@tronto.net> | 2025-01-17 07:52:02 +0100 |
| commit | d0f3f64bb42ea8194c20f0eadd35821cab346143 (patch) | |
| tree | 84355ea4008769382a8300aa11b2b43fd9dd86c1 /templates/pair.cpp | |
| parent | 873ae98050baf54a9a17ac54896de732134206af (diff) | |
| download | taming-cpp-d0f3f64bb42ea8194c20f0eadd35821cab346143.tar.gz taming-cpp-d0f3f64bb42ea8194c20f0eadd35821cab346143.zip | |
Started work on templates article
Diffstat (limited to '')
| -rw-r--r-- | templates/pair.cpp | 35 |
1 files changed, 35 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 | |||
| 3 | template <typename S, typename T> | ||
| 4 | class Pair { | ||
| 5 | public: | ||
| 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 | |||
| 16 | int 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 | } | ||
