« Templates in C++

Pair.cpp

1template <typename T, typename V>
2
3class Pair
4{
5 T x;
6 V y;
7
8public:
9 void setX(T x)
10 {
11 this->x = x;
12 }
13
14 T getX()
15 {
16 return this->x;
17 }
18
19 void setY(V y)
20 {
21 this->y = y;
22 }
23
24 V getY()
25 {
26 return y;
27 }
28};

PairUse.cpp

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13
14#include "Pair.cpp"
15int main()
16{
17 Pair<int, double> p;
18 p.setX(34);
19 p.setY(23423.4);
20 cout << p.getX() << " " << p.getY() << endl;
21
22 cout << "----------------------------------------------------------------" << endl;
23 Pair<Pair<int, int>, int> p1;
24 p1.setY(123456);
25 Pair<int, int> p2;
26 p2.setX(6789);
27 p2.setY(24556);
28 p1.setX(p2);
29 cout << p1.getY() << " " << p1.getX().getX() << endl;
30
31 return 0;
32}