问题
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