![](/img/trans.png)
[英]Passing class instance and method as argument to another function in C++
[英]passing a function as an argument to a method c++
在論壇上搜索答案后,我似乎無法解決此問題。
出於教學目的,我正在創建(模板)鏈接列表類。 我的課有以下方法:
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報告:
沒有匹配的成員函數來調用“ hasValue”
我似乎找不到任何在線解釋為什么會這樣。
你不想要類似的東西嗎
if ((*fn)(c->value,value)) {...}
另外,我建議將參數作為const引用傳遞。
另外,由於這是模板函數,您確定要在聲明的同一頭文件中定義該函數嗎?
您可以使用通用比較器概念:
template <typename E, typename Comp>
bool List<E>::hasValue(E value, Comp fn) { ... }
這樣就可以避免指定函數簽名的需要(它實際上一無所獲)。
然后,您可以將其稱為:
list.hasValue(record{"duder", 20}, std::equal_to<record>());
其中std::equal_to
是從<functional>
導入的。 該函子將調用operator==
如果存在)。
實際上,出於語義目的,如果未明確定義比較器,我還建議自動在hasValue
定義中默認使用std::equal_to
:
template <typename E, typename Comp = std::equal_to<E>>
bool List<E>::hasValue(E value, Comp fn = {}) { ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.