2012-12-19 124 views
4

我試圖用GCC 4.7.2比較兩套C++ 11 weak_ptr。下面的代碼顯示可能的最小樣本再現錯誤:比較兩套std :: weak_ptr

std::set<std::weak_ptr<int>, std::owner_less<std::weak_ptr<int> > > set1; 
std::set<std::weak_ptr<int>, std::owner_less<std::weak_ptr<int> > > set2; 

bool result = (set1 == set2); 

試圖編譯中的錯誤的一個長列表,該列表的下面是第一實際誤差以上的結果:

/usr/include/c++/4.7/bits/stl_algobase.h:791:6: error: no match for ‘operator==’ in ‘__first1.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >() == __first2.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >()’ 

由於到weak_ptr的短暫性質,是比較一整套他們不可能?

更新:

一個建議是使用:

bool result = !((set1 < set2) || (set2 < set1)) 

這導致:

/usr/include/c++/4.7/bits/stl_algobase.h:882:6: error: no match for ‘operator<’ in ‘__first1.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >() < __first2.std::_Rb_tree_const_iterator<_Tp>::operator*<std::weak_ptr<int> >()’ 

回答

4

由於weak_ptr的不支持 '==',但在這你可以使用比較運算符的套件試試:

bool result = !(std::lexicographical_compare(set1.begin(), set1.end(), 
             set2.begin(), set2.end(), 
             set1.value_comp()) || 
       std::lexicographical_compare(set2.begin(), set2.end(), 
             set1.begin(), set1.end(), 
             set1.value_comp())); 

這將測試等價性,而不是等式。它缺乏一定的...清晰度。

+0

我編輯了我的問題並對您的最初建議發表了評論。我注意到你更新了答案,我一定會試一試。爲了教育目的,我將保留原始編輯。 – Hans

+0

此外,我認爲,因爲我指定std :: owner_less作爲比較運算符,所以weak_ptr是否實現'=='應該沒有關係? – Hans

+1

@Hans:是的,我輸入後意識到它將會遇到'operator <',它有相同的問題。因此將其更改爲手動版本,可以使用指定的比較運算符。此外,我的第一次編輯的拼寫有點:) –