为什么C ++关联容器的谓词默认情况下不透明? [英] Why C++ associative containers predicate not transparent by default?
问题描述
自C ++ 14起,我们有 std :: less< void>
在大多数情况下透明且更有用,所以有理由为什么,例如 std :: set
仍默认具有 std :: less< Key>
作为谓词,而不是 std :: less< void>
,除非历史原因。
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> :: find
与 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 ++关联容器的谓词默认情况下不透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!