如何正确实现Song类operator()以支持list::remove_if与std::function?
Song::operator() Implementation Let's get your Song::operator() working correctly, following both of your requirements. Here's the breakdown and corrected code:
Step 1: Invoke the Callback First
The first thing your function needs to do is call the callback_ member. Since it's a std::function<void()>, you can invoke it directly like any other function.
Step 2: Correct the Matching Logic
Your original implementation had a critical flaw: when both title_ and artist_ are empty, it only matched songs with empty title and artist (instead of all songs). Additionally, the conditional logic was more verbose than needed.
The right approach is to check two independent conditions, then combine them with &&:
- The current instance's
title_is either empty (wildcard) OR matches the input song's title - The current instance's
artist_is either empty (wildcard) OR matches the input song's artist
This covers all your required cases:
- Both fields empty → matches every song
- Only title empty → matches all songs by the specified artist
- Only artist empty → matches all songs with the specified title
- Both fields non-empty → matches only exact title+artist matches
Corrected Code
bool Song::operator()(const Song& s) const { // Fulfill requirement 1: call the callback first callback_(); // Fulfill requirement 2: wildcard-based matching bool titleMatches = title_.empty() || (title_ == s.title_); bool artistMatches = artist_.empty() || (artist_ == s.artist_); return titleMatches && artistMatches; }
Bonus: Simplify Playlist::RemoveSongs
With this corrected operator, you can actually remove the initial if (title == "" && artist == "") check in RemoveSongs—the operator will handle matching all songs automatically when given an empty title and artist. The function will work the same way with less redundant code.
内容的提问来源于stack exchange,提问作者salim.p

