c++ - 调用非静态函数作为谓词?

标签 c++ function non-static remove-if

我想使用一个非静态函数作为谓词。不幸的是,我收到一个错误,提示它是非静态的,我不确定如何处理这个问题。

错误:

error: call to non-static member function without an object argument songs_.remove_if(Song::operator()(s) );

这是我结合 remove_if 使用的非静态函数:

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_if 使用该函数作为谓词,如下所示:

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);
});

关于c++ - 调用非静态函数作为谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50420388/

相关文章:

java - 从另一个类访问非静态变量

c++ - 将运算符重载作为模板参数传递

javascript - 如何在选项卡更改时停止 jquery js 功能?

javascript - 如果再次调用,函数中的 mouseEvent 会触发两次?

javascript - 将函数返回的值打印到 javascript 中的屏幕

java - 不能从静态上下文中引用非静态方法

java - 如何解决此错误,无法从静态上下文引用非静态方法

c++ - STL容器的difference_type typedef

c++ - 如何以低于相机每秒帧数的能力处理数据?

c++ - sqlite3_step() 似乎不起作用