为什么这个运算符<重载函数对 STL 算法不可见?

Why is this operator< overload function invisible to STL algorithms?

本文关键字:算法 STL 函数 重载 运算符 lt 为什么      更新时间:2023-10-16

我已经学会了重载operator<,以便使自定义类与STL算法兼容,就像这样:

struct A
{ int a; };
bool operator< (const A& x, const A& y)
{ return x.a < y.a; }
std::vector<A> aOne, aTwo, aResult;
std::set_difference(aOne.begin(), aOne.end(),
aTwo.begin(), aTwo.end(),
std::inserter(aResult, aResult.begin()));

然而,当我尝试对JUCE库中的ValueTree对象执行同样的操作时,它失败了:

bool operator< (const juce::ValueTree& x, const juce::ValueTree& y)
{
// let's now worry about the implementation of this function here...
return true;
}
std::vector<juce::ValueTree> vOne, vTwo, vResult;
std::set_difference(vOne.begin(), vOne.end(),
vTwo.begin(), vTwo.end(),
std::inserter(vResult, vResult.begin()));
// COMPILER ERROR: Failed to specialize function template 'unknown-type std::less<void>::operator ()(_Ty1 &&,_Ty2 &&) const'    

有人能看到我的operator<函数出了什么问题吗?

我知道答案可能与ValueTree的内部工作有关,因此这是一个不完美的问题。但我不知道类型的东西会在这里出错。在我看来,这两种情况似乎完全对称,所以我不知道为什么一种会失败,而另一种会成功。

请注意:我知道我的数组没有排序,因此set_difference会抛出一个异常。现在我只是想编译代码,并保持示例的简洁性。

要被ADL找到,您必须将运算符放在与类相同的命名空间中:

namespace juce
{
bool operator< (const ValueTree& lhs, const ValueTree& rhs) { /*..*/ }
}