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

Why C++ associative containers predicate not transparent by default?(为什么 C++ 关联容器谓词默认不透明?)
本文介绍了为什么 C++ 关联容器谓词默认不透明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于为什么 C++ 关联容器谓词默认不透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What is the proper function for comparing two C-style strings?(比较两个 C 风格字符串的正确函数是什么?)
Image Capture with OpenCV - Select Timeout Error(使用 OpenCV 捕获图像 - 选择超时错误)
SHA256 HMAC using OpenSSL 1.1 not compiling(使用 OpenSSL 1.1 的 SHA256 HMAC 未编译)
How to make a Debian package depend on multiple versions of libboost(如何制作一个Debian包依赖于多个版本的libboost)
Why does strcpy_s not exist anywhere on my system?(为什么我系统上的任何地方都不存在 strcpy_s?)
Simplest way to get current time in current timezone using boost::date_time?(使用 boost::date_time 在当前时区获取当前时间的最简单方法?)