The following code doesn't compile:
#include <iostream>
using namespace std;
class A {
int data;
bool (*comparer)(int, int);
bool defaultComparer(int x, int y) {
return x == y;
}
public:
A() {
comparer = defaultComparer;
}
A(bool (*foo)(int, int)) {
comparer = foo;
}
};
bool myfunc(int a, int b) {
return a == b;
}
int main()
{
A obj(myfunc);
}
The compilation error is:
11:12: error: cannot convert 'A::defaultComparer' from type 'bool (A::)(int, int)' to type 'bool (*)(int, int)'
comparer = defaultComparer;
^
What is the problem with my code? Is it wrong to assign comparer
from defaultComparer
? If yes, then how should I do this?
This is different to "Function pointer to member function", as I don't want to change the type of comparer
.