Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Dec 9, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Write a Generic Function that Takes Variable Datatype Parameters

To write a function like swap(datatype1, datatype2) that will take any two datatypes in its parameter and swap their values, use function templates.

For example, to implement a generic swap function:
//declare the function
template <class T> void swap(T &a, T &b)
 //decleare a temporary placeholder
 T temp;
 temp = a;
 a = b;
 b = temp;

//now to demonstrate ...
#include <iostream>
using namespace std;
int main()
 //decleare some variables for swapping
 int i = 2, j = 3;
 char a = 'a', b = 'b';

 cout<<"Before swapping the integers .. "<<i<<" "<<j<<endl;
 swap(i, j);
 cout<<"after swapping the integers .. "<<i<<" "<<j<<end;
  cout<<"Before swapping the characters .. "<<a<<" "<<b<<endl;
 swap(a, b);
 cout<<"after swapping the characters .. "<<a<<" "<<b<<end;

 return 0;

Before swapping the integers .. 2 3
After swapping the integers .. 3 2
Before swapping the characters .. a b
Before swapping the integers .. b a
Tanzim Husain
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date