C++ 调用非静态函数作为谓词?
我想使用一个非静态的函数作为谓词。不幸的是,我收到一个错误,抱怨它是非静态的,我不确定如何处理这个问题 错误: 错误:在没有对象参数的情况下调用非静态成员函数 如果(Song::operator()(s)),则删除歌曲 以下是我与remove_组合使用的非静态函数,如果:C++ 调用非静态函数作为谓词?,c++,function,non-static,remove-if,C++,Function,Non Static,Remove If,我想使用一个非静态的函数作为谓词。不幸的是,我收到一个错误,抱怨它是非静态的,我不确定如何处理这个问题 错误: 错误:在没有对象参数的情况下调用非静态成员函数 如果(Song::operator()(s)),则删除歌曲 以下是我与remove_组合使用的非静态函数,如果: bool Song::operator()(const Song& s) const { SongCallback(); string thisArtist = Song::artist_;
bool Song::operator()(const Song& s) const
{
SongCallback();
string thisArtist = Song::artist_;
string thisTitle = Song::title_;
// check if songs match title AND artists
if(Song::operator==(s))
{
return true;
// wild card artist or title
}
else if(thisArtist == "" || thisTitle == "")
{
return true;
// either artist or title match for both songs
// }
// else if(thisArtist == s.GetArtist() or thisTitle == s.GetTitle()){
// return true;
// no matches
}
else
{
return false;
}
}
在另一个函数中,我尝试调用remove_,如果使用该函数作为谓词,如下所示:
Song s = Song(title,artist);
songs_.remove_if(s.operator()(s) );
所以我的问题是,我如何正确地调用这个操作符,而不让它抱怨它是一个非静态函数?我在某个地方读到过指向类实例的指针,但这是我能找到的最接近的东西。试试这个:
Song s(title, artist);
songs_.remove_if([&s](const Song& x) { return x(s); });
但是,将比较逻辑作为重载函数调用操作符的一部分是非常奇怪的。如果我不得不猜测的话,我会说你可能会想出一个更干净的设计,例如:
songs_.remove_if([&s](const Song& x) {
return laxly_equal_with_callback(x, s);
});
我将重新组织它,使实现更优雅。非常感谢。