为什么 C++ 关联容器谓词默认不透明?
Why C++ associative containers predicate not transparent by default?
自从 C++14 我们有 std::less<void>
在大多数情况下它是透明的并且更有用,所以有什么原因,例如,std::set
仍然有 std::less<Key>
作为默认谓词,不是 std::less<void>
除了历史原因。
有用案例:std::set<std::string>::find
与std::string_view
等
这样做会破坏当前的工作代码。想象一下我有
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
没有 operator <
.
自从 C++14 我们有 std::less<void>
在大多数情况下它是透明的并且更有用,所以有什么原因,例如,std::set
仍然有 std::less<Key>
作为默认谓词,不是 std::less<void>
除了历史原因。
有用案例:std::set<std::string>::find
与std::string_view
等
这样做会破坏当前的工作代码。想象一下我有
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
没有 operator <
.