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// template specialization
2#include <iostream>
3using namespace std;
4
5// class template:
6template <class T>
7class mycontainer {
8 T element;
9 public:
10 mycontainer (T arg) {element=arg;}
11 T increase () {return ++element;}
12};
13
14// class template specialization:
15template <>
16class mycontainer <char> {
17 char element;
18 public:
19 mycontainer (char arg) {element=arg;}
20 char uppercase ()
21 {
22 if ((element>='a')&&(element<='z'))
23 element+='A'-'a';
24 return element;
25 }
26};
27
28int main () {
29 mycontainer<int> myint (7);
30 mycontainer<char> mychar ('j');
31 cout << myint.increase() << endl;
32 cout << mychar.uppercase() << endl;
33 return 0;
34}
1template<class T1 , class T2>
2float fun(T1 a, T2 b){
3 float avg2 = (a+b)/2.0;
4 return avg2;
5}