簡體   English   中英

無法滿足范圍約束::count()

[英]Unable to Satisfy Constraint for ranges::count()

我正在探索范圍函數。

struct User
{
    std::string name;
    int age;
    std::string gender;

    template<class Os> friend
        Os& operator<<(Os& os, User const& u)
    {
        return os << "\n" << std::right << std::setw(10)
            << u.name << " - " << u.age << ", " << u.gender;
    }
};

std::vector<User> users = {
    {"Dorothy", 59, "F"},
    {"Allan", 60, "M"},
    {"Kenny", 33, "M"},
    {"Jaye", 30, "F"}
};

int main()
{
    std::cout << "Count of M users: " <<
         std::ranges::count_if(users, [](const User& u) {return u.gender == "M"; }) << 
         std::endl;
    
    const User match { "Ed", 44, "M" };

    std::cout << "Count of Ed users: " <<
         std::ranges::count(users, match) <<
         std::endl;
}

count_if 按預期運行。 計數表達式在 MSVS 2019 中生成錯誤。

錯誤 C7602 'std::ranges::_Count_fn::operator ()': 不滿足關聯的約束 D:\Test\Code\Ranges\Ranges.cpp

它指向我的標准算法 header。 我顯然不理解為計數 function 列出的唯一約束的indirect_binary_predicate。 閱讀 cppreference.com 是……沒有幫助:-)。

我在這里想念什么?

std::ranges::count_if您提供自定義比較器。 但是,在std::ranges::count中,您嘗試使用默認比較,但事實並非如此。

您需要提供它,並且假設您想要對結構成員進行逐個比較,您可以簡單地添加:

auto operator<=>(User const &) const = default;

到你的結構。

如果您想要不同類型的比較,則必須指定它而不是使用= default

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM