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

旧时模样 提交于 2019-12-20 02:30:03

问题


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.

Useful cases: std::set<std::string>::find with std::string_view, etc.


回答1:


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;

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 <.



来源:https://stackoverflow.com/questions/54135237/why-c-associative-containers-predicate-not-transparent-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!