1
0

funtemp.cpp 915 B

1234567891011121314151617181920212223242526272829303132333435
  1. // funtemp.cpp -- using a function template
  2. #include <iostream>
  3. // function template prototype
  4. template <typename T> // or class T
  5. void Swap(T &a, T &b);
  6. int main()
  7. {
  8. using namespace std;
  9. int i = 10;
  10. int j = 20;
  11. cout << "i, j = " << i << ", " << j << ".\n";
  12. cout << "Using compiler-generated int swapper:\n";
  13. Swap(i,j); // generates void Swap(int &, int &)
  14. cout << "Now i, j = " << i << ", " << j << ".\n";
  15. double x = 24.5;
  16. double y = 81.7;
  17. cout << "x, y = " << x << ", " << y << ".\n";
  18. cout << "Using compiler-generated double swapper:\n";
  19. Swap(x,y); // generates void Swap(double &, double &)
  20. cout << "Now x, y = " << x << ", " << y << ".\n";
  21. // cin.get();
  22. return 0;
  23. }
  24. // function template definition
  25. template <typename T> // or class T
  26. void Swap(T &a, T &b)
  27. {
  28. T temp; // temp a variable of type T
  29. temp = a;
  30. a = b;
  31. b = temp;
  32. }