在使用二元谓词的find_first_of函数上给出错误

gives error on find_first_of function with binary predicate

本文关键字:of first 函数 错误 出错 find 谓词 二元      更新时间:2023-10-16

代码

#include <string>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class test {
    struct con {
        string s1;
        string s2;
    };
public:
    void somefunc();
private:
    bool pred(con c1, con c2);
    vector<con> vec;
};
void test::somefunc()
{
    vector<con> v;
    vector<con>::iterator it = find_first_of(vec.begin(), vec.end(), v.begin(), v.end(), pred);
}
bool test::pred(con c1, con c2)
{
    return 0;
}

给出错误

est.cpp(24):错误C2664: 'struct test::con *__cdecl std::find_first_of(struct test::con *,struct test::con *,struct test::con *,struct test::con *,struct test::con *,struct test::con *,struct test::con *,bool (__thiscall *)(struct test::con不能将参数5从bool (struct test::con,struct test::con)'转换为bool (__thiscall *)(struct test::con,struct test::con)'作用域中没有一个具有此名称的函数匹配目标类型

我不明白什么是(__thiscall*)以及如何将我的谓词函数转换为它

谓词不能是非静态成员函数,因为它接受隐式的第一个参数,总共给出三个参数。您要么需要静态成员函数,要么需要非成员函数:

// non-member function
bool pred(const con& c1, const con& c2)
{
    return false;
}
void test::somefunc()
{
  vector<con> v;
  vector<con>::iterator it = find_first_of(vec.begin(), vec.end(), 
                                           v.begin(), v.end(), 
                                           pred);
}

或者,使用std::bind绑定this作为第一个参数:

using namespace std::placeholders;
vector<con>::iterator it = find_first_of(vec.begin(), vec.end(), 
                                         v.begin(), v.end(),
                                         std::bind(&test::pred, this, _1, _2));

std::bind的调用产生一个具有两个con参数的可调用实体。它在内部存储this指针的副本(但this不用于pred函数)。

__thiscall是仅msvc++用于非静态成员函数的调用约定。

在您的代码中,pred是一个非静态成员函数,如果没有std::bind之类的解决方案,它不能用作二进制谓词。我建议你把这个函数设为static。或者更好地使用lambda(仅限c++ 11)。

谓词是一个非静态成员函数。要么将其设为静态(或简单地设为非成员函数),要么使用std::bind()(或等效的Boost)。如果你负担不起c++ 11)绑定:

#include <functional>
// ...
vector<con>::iterator it = find_first_of(
    vec.begin(), vec.end(), v.begin(), v.end(),
    std::bind(&test::pred, this, std::placeholders::_1, std::placeholders::_2));

下面是一个的实例

如果您选择将函数保留为成员函数并使用std::bind(),请考虑将函数pred()限定为const,因为应该改变调用它的对象的状态。