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

2022-01-24 00:00:00 containers c++ associative predicate

从 C++14 开始,我们有 std::less<void>,它在大多数情况下是透明且更有用的,所以有没有理由,例如,std::set 默认情况下仍然有 std::less 作为谓词,而不是 std::less 除非历史原因.

Since C++14 we have std::less<void> that is transparent and more usefull in most cases, so is there reasons why, for example, std::set still has std::less<Key> as a predicate by default, not an std::less<void> except historical reasons.

用例:std::set::findstd::string_view

推荐答案

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

It would break current working code to do so. Imagine I have

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 可以没有 运算符 <.

If std::set was changed to use std::less<void> then this code would no longer compile since my_type does not have an operator <.

相关文章