Template Array

A.First Edition
This is first edition of my little test program to use a template function array. Or in other words, how to
declare a function pointer array that holds some uniformed template functions, say a series of sorting functions.
B.The problem
There is no way to directly declare a function array as template function will never be compiled until it is 
used! Or instanciated! So, you cannot put them into array by initializing, instead you have to "make them 
instanciate" by passing the parameter to template. You can do this by declare another function pointer to
represent template function.
C.The idea of program
กก

This is only a small test, if you understand it. Then I think we can have some common topic.

D.The major functions
C.Further improvement
#include <iostream>

using namespace std;

//three different sorting function declared in template
template <class Elem>
void bubbleSort(Elem array[], int size);

template <class Elem>
void selectSort(Elem array[], int size);

template <class Elem>
void quickSort(Elem array[], int size);

//here I have to declare function pointer to "instanciate the template
//otherwise compiler won't start compile template until it is in use
void (*fun1)(int array[], int size)=bubbleSort<int>;
void (*fun2)(int array[], int size)=selectSort<int>;
void (*fun3)(int array[], int size)=quickSort<int>;

//this is really what I intend to use---to declare a function array to 
//hold the function pointer to 
void (*sortFun[3])(int array[], int size)={fun1, fun2, fun3};

int main()
{
	int myArray[6]={0,2,6,3,4,1};
	
	for (int i=0; i<3; i++)
	{
		//this will correctly call all template functions.
		(*sortFun[i])(myArray, 6);
	}
	return 0;
}

//the implementation of all sorting algorithms are omitted here.
template <class Elem>
void bubbleSort(Elem array[], int size)
{
	cout<<"this is a function of bubble sorting\n";
	for (int i=0; i<size; i++)
	{
		cout<<array[i]<<"\t";
	}
	cout<<endl;
	
}

template <class Elem>
void selectSort(Elem array[], int size)
{
	cout<<"this is a function of selection sorting\n";
	for (int i=0; i<size; i++)
	{
		cout<<array[i]<<"\t";
	}
	cout<<endl;
}

template <class Elem>
void quickSort(Elem array[], int size)
{
	cout<<"this is a function of quick sorting\n";
	for (int i=0; i<size; i++)
	{
		cout<<array[i]<<"\t";
	}
	cout<<endl;
}





The following result is to prove the function array does work!
this is a function of bubble sorting
0 2 6 3 4 1
this is a function of selection sorting
0 2 6 3 4 1
this is a function of quick sorting
0 2 6 3 4 1
Press any key to continue

                                 back.gif (341 bytes)       up.gif (335 bytes)         next.gif (337 bytes)