Function template: swap values : Function Template « Function « C++






Function template: swap values

Function template: swap values
 


#include <iostream>
using namespace std;

template <class X> void swapargs(X &a, X &b)
{
  X temp;

  temp = a;
  a = b;
  b = temp;
}

int main()
{
  int i=10, j=20;
  float x=10.1, y=23.3;

  cout << "Original i, j: " << i << ' ' << j << endl;
  cout << "Original x, y: " << x << ' ' << y << endl;

  swapargs(i, j); // swap integers
  swapargs(x, y); // swap floats

  cout << "Swapped i, j: " << i << ' ' << j << endl;
  cout << "Swapped x, y: " << x << ' ' << y << endl;

  return 0;
}


           
         
  








Related examples in the same category

1.A generic mode finding function.A generic mode finding function.
2.Simple template function to accept two parametersSimple template function to accept two parameters
3.template function for find a valuetemplate function for find a value
4.Creating a custom algorithm based on templateCreating a custom algorithm based on template
5.find all template function
6.Using a Binary Function to Multiply Two Ranges
7.Making a Sequence of Random Numbers
8.write function object
9.Use a Function Object to Hold state
10.template function for bubble sort
11.template function for compacting the items
12.Template copy array function
13.function template for getting the max value
14.Overriding a template function.
15.Using Standard Parameters with Template Functions