![](/img/trans.png)
[英]Why STL <set> the overload operator < function must be a const function?
[英]Why is this operator< overload function invisible to STL algorithms?
我已經學會了重載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) { /*..*/ }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.