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>
2using namespace std;
3
4template <typename T>
5void Swap(T &n1, T &n2)
6{
7 T temp;
8 temp = n1;
9 n1 = n2;
10 n2 = temp;
11}
12
13int main()
14{
15 int i1 = 1, i2 = 2;
16 float f1 = 1.1, f2 = 2.2;
17 char c1 = 'a', c2 = 'b';
18
19 cout << "Before passing data to function template.\n";
20 cout << "i1 = " << i1 << "\ni2 = " << i2;
21 cout << "\nf1 = " << f1 << "\nf2 = " << f2;
22 cout << "\nc1 = " << c1 << "\nc2 = " << c2;
23
24 Swap(i1, i2);
25 Swap(f1, f2);
26 Swap(c1, c2);
27
28 cout << "\n\nAfter passing data to function template.\n";
29 cout << "i1 = " << i1 << "\ni2 = " << i2;
30 cout << "\nf1 = " << f1 << "\nf2 = " << f2;
31 cout << "\nc1 = " << c1 << "\nc2 = " << c2;
32
33 return 0;
34}
35
1// function template
2#include <iostream>
3using namespace std;
4
5template <class T>
6T GetMax (T a, T b) {
7 T result;
8 result = (a>b)? a : b;
9 return (result);
10}
11
12int main () {
13 int i=5, j=6, k;
14 long l=10, m=5, n;
15 k=GetMax<int>(i,j);
16 n=GetMax<long>(l,m);
17 cout << k << endl;
18 cout << n << endl;
19 return 0;
20}
1// template function
2template <class T>
3T Large(T n1, T n2)
4{
5 return (n1 > n2) ? n1 : n2;
6}
1template < typename T >
2inline T max ( T a , T b ) {
3 return a > b ? a : b ;
4}
5
6int main ()
7{
8 // Isso chamará max <int> por dedução implícita do argumento.
9 std :: cout << max ( 3 , 7 ) << std :: endl ;
10
11 // Isso chamará max <double> por dedução implícita do argumento.
12 std :: cout << max ( 3.0 , 7.0 ) << std :: endl ;
13
14 // Isso depende do compilador. Alguns compiladores lidam com isso definindo uma
15 função de
16 modelo // como double max <double> (double a, double b) ;, enquanto em alguns compiladores // precisamos convertê-lo explicitamente, como std :: cout << max <double> (3,7,0);
17 std :: cout << max ( 3 , 7.0 ) << std :: endl ;
18 std :: cout << max < double > ( 3 , 7.0 ) << std :: endl ;
19 return 0 ;
20}