当前位置: 动力学知识库 > 问答 > 编程问答 >

overloading - passing a function as an argument to a method c++

问题描述:

After searching the forum for an answer I cannot seem to resolve this issue.

For pedagogical purposes I'm creating a (template) linked list class. My class has the following method:

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;

}

I want bool (*fn)(E, E) to be any overloaded operator== defined by the user like so:

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;

}

however if i call list.hasValue({"duder", 20}, operator==) Xcode reports:

No matching member function for call to 'hasValue'

I can't seem to find any online explanation of why this is occurring.

网友答案:

don't you want something like

 if ((*fn)(c->value,value)) {...}

also , I suggest passing the arguments as const references.

Also, since this is a template function , are you sure you're defining the function in the same header file it's declared?

网友答案:

You can use a generic comparator concept:

template <typename E, typename Comp>
bool List<E>::hasValue(E value, Comp fn) { ... }

this lets you avoid the need to specify the function signature (which really gains you nothing).

Then you can call it as:

list.hasValue(record{"duder", 20}, std::equal_to<record>());

where std::equal_to is imported from <functional>. This functor will call operator== if it exists.


In fact I would also recommend, for semantic purposes, to automatically default to using std::equal_to in your hasValue definition if the comparator is not explicitly defined:

template <typename E, typename Comp = std::equal_to<E>>
bool List<E>::hasValue(E value, Comp fn = {}) { ... }
分享给朋友:
您可能感兴趣的文章:
随机阅读: