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.

WolfPack commented: For proper use of code tags. +7

Recommended Answers

All 2 Replies

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.