Monday, July 25, 2011

Function pointer and templates

Here are a couple of silly functions that show the use of Function pointers and templates. Function pointers are pointers to functions with a particular signature. In our case the function points to any function that returns and integer and takes two integer values. Pointer functions are closely related to Delegates in C#.

Templates are called Generics in C# and Java. they are functions or classes whose data type is not determined until run time. Both of these tools can prove a valuable way to manage code for scalability and flexibility.

We used three files. First I will show the header file. This file contains all the function prototypes and the complete template function. You cannot separate a template function's implementation from its type declaration.


AdvancedFunctions.h

int Add(int, int);
int Subtract(int, int);
int Multiply(int, int);
int Divide(int, int);
void DoMath(int, int, int(*pfunction)(int, int));

template <typename any>
void Addition(any a, any b)
{
cout << a + b << endl;
}


Here is the Function definition file:


FunctionDefinitions.cpp

#include <iostream>
#include "AdvancedFunctions.h"

using namespace std;

int Add (int n1, int n2)
{
return n1+n2;
}

int Subtract(int n1,int n2)
{
return n1-n2;
}

int Multiply(int n1, int n2)
{
return n1*n2;
}

int Divide(int n1, int n2)
{
int quotient=0;
if (n2 !=0)
{
quotient=n1/n2;
}
return quotient;
}

void DoMath(int n1, int n2, int(*pfunction)(int , int ))
{
cout << pfunction(n1,n2) << endl;
}


And lastly, here is the Program file with the main:


Program.cpp

#include <iostream>
#include "AdvancedFunctions.h"
#include <string>

using namespace std;

int main()
{
DoMath(5,7,Add);
cout << endl;
DoMath(13,4,Subtract);
cout << endl;
DoMath(13,4,Multiply);
cout << endl;
DoMath(13,4,Divide);

Addition(6,7);
Addition(4.3345,13.567);
string x = "hello";
string y="World";
Addition(x,y);
char c;
cin >> c;
}

No comments:

Post a Comment