为什么 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 与 std::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++ 关联容器谓词默认不透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
