将类成员函数指针传递给另一个函数

c++ passing class member function pointer to another function

本文关键字:函数 另一个 指针 成员      更新时间:2023-10-16

我在互联网上搜索,我找到了一些解决方案,但我不想改变我的整个代码。我想在vector<my_class *>中搜索一个不同的对象,所以我写了这个,但它不起作用:

static vector <attendant *> attendant_vec;
template<typename T, typename R>
int binary_search(int first_cell, int last_cell,int search_key, vector<T*>& v, R (T::*func)(void), void *sort){
    int index;
    quicksort(v, v.size(), 0, sort);
    if(first_cell > last_cell)
        return -1;
    else {
        int middle = (first_cell + last_cell)/2;
        if(search_key== v.at(middle).*func())
            index=middle;
        else
            if(search_key< v.at(middle).*func())
                index=binary_search(first_cell, middle-1, search_key, v, func,sort);
            else
                index=binary_search(middle+1, last_cell, search_key, v, func,sort);
    }
    return index;
}
void my_function() {
    int u = binary_search(0,attendant_vec.size(),12,
            attendant_vec,&attendant::get_personal_code,
            &sort_by_personal_code);//ERROR
    cout<<u;
}

我有这些错误:

此行有多个标记

  • 没有匹配的函数来调用binary_search(int, std::vector::size_type, int, std::vector&, int)(服务员::)()常量,布尔值()(服务员,服务员*))
  • 候选人:
  • 导出参数' _filter ' (' int '和' long unsigned int ')的冲突类型
  • 类型' R (T::)() '和' int(服务员::)()const '具有不兼容的cv限定符

您可以这样使用std::binary_search:

void my_function() {
    int u = std::binary_search(attendant_vec.begin(), attendant_vec.end(), 12, &sort_by_personal_code);
    std::cout << u;
}