在论坛上搜索答案后,我似乎无法解决这个问题。
出于教学目的,我正在创建一个(模板)链表类。我的类(class)有以下方法:
template <typename E>
bool List<E>::hasValue(E value, bool (*fn)(E, E)){
bool hasValue = false;
node* c = head;
while (true) {
if (c->value == value) {
hasValue = true;
break;
}
else if (c->next != 0) {
c = c->next;
}
else {
break;
}
}
return hasValue;
}
我希望 bool (*fn)(E, E)
是用户定义的任何重载运算符==,如下所示:
struct record {
string name;
int age;
};
bool operator==(const record& r1, const record& r2) {
bool result = false;
if (r1.name == r2.name && r1.age == r2.age) {
result = true;
}
return result;
}
但是如果我调用 list.hasValue({"duder", 20}, operator==)
Xcode 报告:
No matching member function for call to 'hasValue'
我似乎无法在网上找到任何关于为什么会发生这种情况的解释。
最佳答案
你不想要类似的东西吗
if ((*fn)(c->value,value)) {...}
另外,我建议将参数作为常量引用传递。
此外,由于这是一个模板函数,您确定要在声明的同一个头文件中定义该函数吗?
关于c++ - 将函数作为参数传递给方法 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28395838/