1template <class T>
2void swap(T & lhs, T & rhs)
3{
4 T tmp = lhs;
5 lhs = rhs;
6 rhs = tmp;
7}
1template <class T>
2void swap(T & lhs, T & rhs)
3{
4 T tmp = lhs;
5 lhs = rhs;
6 rhs = tmp;
7}
8
9void main()
10{
11 int a = 6;
12 int b = 42;
13 swap<int>(a, b);
14 printf("a=%d, b=%d\n", a, b);
15
16 // Implicit template parameter deduction
17 double f = 5.5;
18 double g = 42.0;
19 swap(f, g);
20 printf("f=%f, g=%f\n", f, g);
21}
22
23/*
24Output:
25a=42, b=6
26f=42.0, g=5.5
27*/
1#include <iostream>
2#include <string>
3using namespace std;
4
5
6template <class calculator> //Template Definition
7
8calculator addNumber(calculator A, calculator B) {
9 return A + B;
10}
11
12int main() {
13
14 int a = 7, b = 55;
15
16 float x = 77.77, y = 8.99;
17
18 double u = 4.44, v = 7.88;
19
20 string i = "My ", j = "God!";
21
22
23
24 std::cout << addNumber(a, b) << endl;
25
26 std::cout << addNumber(x, y) << endl;
27
28 std::cout << addNumber(u, v) << endl;
29
30 std::cout << addNumber(i, j) << endl;
31}
32
33//Build Generic Function that can handle multiple type of data