Search code examples
c++ooptemplatesfunction-pointerspointer-to-member

Member template function pointers errors


I am using a pointer to a template member function as follows in my "Array" class :

//Sorts elements according to the value of sortFn (ascending)
template<typename T>
template<typename S>
void Array<T>::sort(int (S::*sortFn)())
{
    quickSort(0, size - 1, &S::sortFn);
}

//Sorts elements according to the value of sortFn (ascending) using quicksort.
template<typename T>
template<typename S>
void Array<T>::quickSort(int start, int pivot, int (S::*sortFn)())
{
    if (start >= pivot)
        return;
    int current = start;
    int wall = start;
    while (current != pivot)
        if ((arr[current]->*sortFn)() < (arr[pivot]->*sortFn)())
        {
            current++;
        }
        else
        {
            swap(arr[current], arr[wall]);
            current++;
            wall++;
        }
    swap(arr[wall], arr[pivot]);
    quickSort(start, wall - 1, &S::sortFn);
    quickSort(wall + 1, pivot, &S::sortFn);

}

So this is just a sort function based on quicksort, that takes an extra function pointer parameter and sorts the array according to the value of this function (called by each element).

I have been using similar implementations throughout the program and they work fine, however, when I try calling this sort function (enemiesList is an object of class Array , getFD is a member function of class Enemy that returns int) :

enemiesList.sort(&Enemy::getFD);

I get these errors :

'sortFn' is not a member of 'Enemy'

Array::quickSort: function does not take 3 arguments

erros

At this line of the sort function :

quickSort(0, size - 1, &S::sortFn);

Please note that there are overloaded versions of sort & quicksort that are implemented exactly the same but without using the function pointer parameter (using < for comparison). Any help??


Edit: I managed to fix the error by replacing the quickSort function call inside sort function to :

quickSort(0, size - 1, sortFn);

Also the 2 recursive call lines inside quickSort:

quickSort(start, wall - 1, sortFn);
quickSort(wall + 1, pivot, sortFn);

I kinda understood that the compiler couldn't tell that sortFn passed to "sort" as an argument wasn't the same as sortFn passed to "quickSort" inside of it. I still don't really understand why this happens and HOW EXACTLY SHOULD I USE templates, function pointers, and classes together ? Can someone please explain to me the right way to do things and how ?

Thanks in advance.


Solution

  • quickSort(0, size - 1, &S::sortFn);
    

    should simply be:

    quickSort(0, size - 1, sortFn);
    

    Same in recursive call:

    quickSort(start, wall - 1, sortFn);
    quickSort(wall + 1, pivot, sortFn);
    

    sortFn is your variable, &S::sortFn is (after template substitution) &Enemy::sortFn, a pointer on (non existent) member sortFn.