This error:
error C2664: ‘Set::Set(int (__cdecl *)(ElemType,ElemType))’
: cannot convert parameter 1 from ‘int (__cdecl
*)(CorrectionT &,CorrectionT &)’ to ‘int (__cdecl *)(ElemType,ElemType)’
is the result of implementing this comparison function as part of a BST based SET class,
int compareCorr(struct CorrectionT &a, struct CorrectionT &b)
{
if (a.editDistance < b.editDistance) return -1;
else if (a.editDistance == b.editDistance) return 0;
else return 1;
}
Class Set
Set(int (*cmpFn)(ElemType, ElemType) = OperatorCmp);
and the use of the comparison function in Set is for add
template <typename ElemType>
void Set<ElemType>::add(ElemType element) {
bst.add(element);
}
And add in the bst class
restating header file
BST(int (*cmpFn)(ElemType one, ElemType two) = OperatorCmp);
and the function add
template <typename ElemType>
bool BST<ElemType>::add(ElemType data) {
bool createdNewNode = false;
recAddNode(root, data, createdNewNode);
if (createdNewNode) timestamp++;
return createdNewNode;
}
template <typename ElemType>
bool BST<ElemType>::recAddNode(nodeT * & t, ElemType & data,
bool & createdNewNode) {
if (t == NULL) {
t = new nodeT;
t->data = data;
t->bf = BST_IN_BALANCE;
t->left = t->right = NULL;
createdNewNode = true;
numNodes++;
return true;
}
int sign = cmpFn(data, t->data);
if (sign == 0) {
t->data = data;
createdNewNode = false;
return false;
}
int bfDelta = 0;
if (sign < 0) {
if (recAddNode(t->left, data, createdNewNode)) {
bfDelta = -1; /* left subtree is higher */
}
} else {
if (recAddNode(t->right, data, createdNewNode)) {
bfDelta = +1; /* right subtree is higher */
}
}
updateBF(t, bfDelta);
return (bfDelta != 0 && t->bf != BST_IN_BALANCE);
}
Any idea what is going on here – what is the problem with the comparison function?
The type of
compareCorrisint(Lexicon::CorrectionT&, Lexicon::CorrectionT &). Its parameters are references.The type of
cmpFn, the parameter of the constructor, isint(*)(ElemType, ElemType). Its parameters are objects (not references).The types must match. Assuming that
ElemTypeisLexicon::CorrectionT, you must either change the function pointer type to have reference parameter types or change the comparer type to have object paramter types. (If you go the reference route, they should both probably use const references, since a comparer should not mutate objects.)Alternatively, you can do what the STL does, and make the comparer a part of the type, allowing usage of arbitrary function objects for comparison. Then, the comparer just needs to have parameters of types compatible with the types of the objects being compared (i.e., things don’t need to match exactly).