fork download
  1. // twotemps.cpp -- using overloaded template functions
  2. #include <iostream>
  3. template <typename T> // original template
  4. void Swap(T &a, T &b);
  5.  
  6. template <typename T> // new template
  7. void Swap(T *a, T *b, int n);
  8.  
  9. void Show(int a[]);
  10. const int Lim = 8;
  11. int main()
  12. {
  13. using namespace std;
  14. int i = 10, j = 20;
  15. cout << "i, j = " << i << ", " << j << ".\n";
  16. cout << "Using compiler-generated int swapper:\n";
  17. Swap(i,j); // matches original template
  18. cout << "Now i, j = " << i << ", " << j << ".\n";
  19.  
  20. int d1[Lim] = {0,7,0,4,1,7,7,6};
  21. int d2[Lim] = {0,7,2,0,1,9,6,9};
  22. cout << "Original arrays:\n";
  23. Show(d1);
  24. Show(d2);
  25. Swap(d1,d2,Lim); // matches new template
  26. cout << "Swapped arrays:\n";
  27. Show(d1);
  28. Show(d2);
  29. // cin.get();
  30. return 0;
  31. }
  32.  
  33. template <typename T>
  34. void Swap(T &a, T &b)
  35. {
  36. T temp;
  37. temp = a;
  38. a = b;
  39. b = temp;
  40. }
  41.  
  42. template <typename T>
  43. void Swap(T a[], T b[], int n)
  44. {
  45. T temp;
  46. for (int i = 0; i < n; i++)
  47. {
  48. temp = a[i];
  49. a[i] = b[i];
  50. b[i] = temp;
  51. }
  52. }
  53.  
  54. void Show(int a[])
  55. {
  56. using namespace std;
  57. cout << a[0] << a[1] << "/";
  58. cout << a[2] << a[3] << "/";
  59. for (int i = 4; i < Lim; i++)
  60. cout << a[i];
  61. cout << endl;
  62. }
  63.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
i, j = 10, 20.
Using compiler-generated int swapper:
Now i, j = 20, 10.
Original arrays:
07/04/1776
07/20/1969
Swapped arrays:
07/20/1969
07/04/1776