1

Is there any way to pass a class as a function pointer.
for example:

int compare(int a, int b)
{
    return a - b;
}

void sort(int *ar, int (*pf)(int, int))
{
    //a sorting algorithm.
}

class MyClass
{
    bool condition;
public:
     int compare(int a, int b)
     {
		 if (condition)
			 return a - b;
		 else
			 return b - a;
     }
};

void main()
{
	int testAr[] = {0, 1, 2, 3};
	sort(testAr, compare);
	//MyClass m;
	//sort(testAr, m.compare);
	return 0;
}

I don't want to use static function instead of member function.

Votes + Comments
For proper use of code tags.
3
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by bugmenot
0

no, it is better that you make the class a functor class (its has an overloaded function call operator); and then you should template the sort function, so it can either take a function pointer or a function object

int compare(int a, int b)
{
    return a - b;
}

template <typename Compare>
void sort(int *ar, Compare pf)
{
    //a sorting algorithm.
}

class MyClass
{
    bool condition;
public:
     int operator()(int a, int b)
     {
		 if (condition)
			 return a - b;
		 else
			 return b - a;
     }
};

void main()
{
	int testAr[] = {0, 1, 2, 3};
	sort(testAr, compare);
	sort(testAr, MyClass);
	return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.