Need help with passing function as argument to other function

Hello.


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.

Here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 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;
	}else if(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'


Could anyone be so nice and help me to fix it?
Last edited on
If you want to pass an array you need to change the first parameter type of DoSomething.

You need to specify what version of compareTo you want to pass to DoSomething.

DoSomething(list,compareTo<int>);
Thank you for your quick response that helped.
Topic archived. No new replies allowed.