Search code examples
c++functionnon-staticremove-if

Calling a Non-Static function as Predicate?


I would like to use a function that is not static as a predicate. Unfortunately I recieve an error complaining about it being non-static and I am unsure how to approach this.

Error:

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

Here is the non-static function that I am using in combination with a 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;
    } 
}

and in another function I am trying to call a remove_if use that function as the predicate like so:

Song s = Song(title,artist);
songs_.remove_if(s.operator()(s) );

So my question is, how do I properly call this operator without it complaining about it being a non-static function? I have read somewhere about a pointer to the class instance but thats the closest thing I could find.


Solution

  • Try this:

    Song s(title, artist);
    songs_.remove_if([&s](const Song& x) { return x(s); });
    

    It's pretty weird, though, to make the comparison logic part of an overloaded function call operator. If I had to guess I'd say that you could probably come up with a much cleaner design, e.g.:

    songs_.remove_if([&s](const Song& x) {
        return laxly_equal_with_callback(x, s);
    });