How to declare and use a pointer to a member function?

Basically, I have the following code: a struct with a quicksort method using cmp1 for comparing. I would like to add a parameter to qsort so I can use it with either cmp1 or cmp2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct X {
	int *l;
	int *r;

	int cmp1(int *p, int *q) { return p - q; }
	int cmp2(int *p, int *q) { return *p - *q; }

	void qsort(int *l, int *r) {
		int *i = l;
		int *j = r;
		int *x = ...;
		do {
			while (cmp1(i, x) < 0) i++;
			...
		}
		...
	}
	inline void Sort() {
		...
		qsort(l, r);
	}
};


I have tried several things from articals all over the web for the last hour but none compiled (with VS 2008), so any help would be appreciated.

Please help, I don't want to end up with two qsort methods - one for cmp1 and the other one for cmp2...
Last edited on
This should be the right way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class X
{
  //...
    typedef int (X::*func_ptr) (int*,int*); // typedef to keep ugly syntax only here
    void qsort(int *l, int *r, func_ptr cmp )
    {
        //...
        while ( (this->*cmp) (i, x) < 0 )
        //...
    }
    void Sort()
    {
        qsort ( l, r, &X::cmp1 );
    }
};
Thanks a lot.
Topic archived. No new replies allowed.