Monday, February 10, 2014

Swap Values With Function Template

Swap values function is commonly used in applications that make operations on arithmetic values such as int,double and float. Instead of implementing overloaded functions for different data types to handle swap operation, function templates can be preferred.

Following sample project created by qt creator and contains following files:
1- UsingTemplatesInCPP.pro
2- main.cpp


UsingTemplatesInCPP.pro file contains project configuration.

TEMPLATE = app
TARGET    = UsingTemplatesInCPP
CONFIG   += console
TEMPLATE  = app
SOURCES  += main.cpp

main.cpp file contains main method and swapValues template function implementations.

#include <stdio.h>

template<typename T>
void swapValues(T &param1, T &param2)
{
    T temp = param1;
    param1 = param2;
    param2 = temp;
}

int main(int argc, char *argv[])
{

 int iP1 = 1, iP2 = 2;
 printf("Initial Integer Values : p1 = %d  p2 = %d \n", iP1, iP2);
 swapValues(iP1,iP2);
 printf("Swapped Integer Values : p1 = %d  p2 = %d \n\n", iP1, iP2);

 double dP1 = 1.34, dP2 = 2.45;
 printf("Initial Double Values : p1 = %f  p2 = %f \n", dP1, dP2);
 swapValues(dP1,dP2);
 printf("Swapped Double Values : p1 = %f  p2 = %f \n\n", dP1, dP2);

 float fP1 = 1.67, fP2 = 2.89;
 printf("Initial Float Values : p1 = %f  p2 = %f \n", fP1, fP2);
 swapValues(fP1,fP2);
 printf("Swapped Float Values : p1 = %f  p2 = %f \n", fP1, fP2);

 return 0;
}

When swapValues template function is called with integer parameters the compiler binds integer values for the generic type parameter T and instantiates an instance of the function template with integer parameters.
The same process is followed when double and float instances are instantiated.
Console output contains all the printf function results as follows :

No comments:

Post a Comment