dude
dude

Reputation: 21

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.

Upvotes: 1

Views: 69

Answers (2)

Shoe
Shoe

Reputation: 76240

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 = {}) { ... }

Upvotes: 1

David Haim
David Haim

Reputation: 26486

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?

Upvotes: 1

Related Questions