You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确实现Song类operator()以支持list::remove_if与std::function?

Fixing 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:40:53