为什么C++关联容器谓词默认不透明

Why C++ associative containers predicate not transparent by default?

本文关键字:谓词 默认 不透明 C++ 关联 为什么      更新时间:2023-10-16

自 C++14 以来,我们std::less<void>在大多数情况下是透明且更有用的,所以是否有原因,例如,默认情况下,std::set仍然将std::less<Key>作为谓词,而不是std::less<void>,除非历史原因。

有用案例:std::set<std::string>::find std::string_view等。

这样做会破坏当前的工作代码。 想象一下我有

struct my_type
{
    int id;
    int bar;
};
namespace std {
    template<>
    struct less<my_type>
    {
        bool operator()(my_type const& lhs, my_type const& rhs)
        {
            return lhs.id < rhs.id; // bar doesn't need to be compared, only need unique id's in the container.
        }
    };
}
std::set<my_type> foo;

如果std::set更改为使用std::less<void>则此代码将不再编译,因为my_type没有operator <