【问题标题】:Why C++ associative containers predicate not transparent by default?为什么 C++ 关联容器谓词默认不透明?
【发布时间】:2019-06-05 17:01:57
【问题描述】:

自 C++14 以来,std::less<void> 在大多数情况下是透明且更有用的,所以有什么原因可以解释为什么,例如,std::set 在默认情况下仍将std::less<Key> 作为谓词,而不是@987654324 @历史原因除外。

用例:std::set<std::string>::findstd::string_view

【问题讨论】:

  • 我认为不会以某种微妙的方式破坏向后兼容性。

标签: c++ containers predicate associative


【解决方案1】:

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

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&lt;void&gt;,则此代码将不再编译,因为my_type 没有operator &lt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 2015-01-10
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多