【发布时间】:2019-01-25 17:26:36
【问题描述】:
我在std::less 的帮助下使用透明比较器偶然发现了std::set 的非常奇怪的编译错误。考虑这个简单的程序:
using Key = std::string;
bool operator<(const Key&, int) { return true; }
bool operator<(int, const Key&) { return true; }
int main()
{
std::set<Key, std::less<>> s;
int x;
auto it = s.find(x);
}
它给了我编译错误:
error: no matching function for call to object of type 'const std::less<void>'
if (__j != end() && _M_impl._M_key_compare(__k, _S_key(__j._M_node)))
^~~~~~~~~~~~~~~~~~~~~~
如果我使用自己的类而不是 std::string 作为键,它可以正常工作:
struct My {};
bool operator<(const My&, const My&) { return true; }
using Key = My;
为什么它不适用于std::string?
在此处查看演示:https://gcc.godbolt.org/z/MY-Y2s
UPD
我真正想做的是在std::unique_ptr<T> 和T* 之间声明比较运算符。但我认为std::string 会更清楚。
【问题讨论】:
-
std::less<Key>,不是吗? -
您将苹果与橙子进行比较。您的
My实现需要 2 个My。您的string实现采用int和string。这要求比较器是透明的。 -
标准是否允许定义不涉及任何用户提供类型的运算符重载?
-
@eerorika
std::string被认为是用户提供的类型。虽然你不应该为你不拥有的类型重载运算符。
标签: c++ compiler-errors stl