twotemps.cpp 1.3 KB

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