I am trying to pass function as argument to another function. My idea is to write function that can works with any type of array, and for it to be able to compare array items I'd like to use my own compareTo function. But I need to be able to pass function to use for comparing argument.
To say it short I am trying to write my own qsort that would take compareTo as one argument just like original qsort does.
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
template <class T>
int compareTo( T a,T b)
{
if(a > b){
return 1;
}elseif(a == b){
return 0;
}else{
return -1;
}
}
template <class T>
void DoSomething(T aLst[],int(__cdecl* pFunc)(T, T)){
int result = pFunc(aLst[0],aLst[1]);
printf("Result: %d\n",result);
}
int main()
{
int list[3] = {1,2,3};
DoSomething(list,compareTo);
system("pause");
return 0;
}
and errors
1 2 3 4
1>d:\my documents\visual studio 2012\projects\test\test\test.cpp(29): error C2896: 'void DoSomething(T,int (__cdecl *)(T,T))' : cannot use function template'int cmp(T,T)' as a function argument
1> d:\my documents\visual studio 2012\projects\test\test\test.cpp(8) : see declaration of 'cmp'
1>d:\my documents\visual studio 2012\projects\test\test\test.cpp(29): error C2784: 'void DoSomething(T,int (__cdecl *)(T,T))' : could not deduce template argument for'T' from 'int [3]'
1> d:\my documents\visual studio 2012\projects\test\test\test.cpp(21) : see declaration of 'DoSomething'