简体   繁体   English

将函数作为参数传递给方法c ++

[英]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: 我希望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;
}

however if i call list.hasValue({"duder", 20}, operator==) Xcode reports: 但是,如果我调用list.hasValue({"duder", 20}, operator==) Xcode报告:

No matching member function for call to 'hasValue' 没有匹配的成员函数来调用“ 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. 另外,我建议将参数作为const引用传递。

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> . 其中std::equal_to是从<functional>导入的。 This functor will call operator== if it exists. 该函子将调用operator==如果存在)。


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: 实际上,出于语义目的,如果未明确定义比较器,我还建议自动在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM