2012-04-15 69 views
6

Test.h==操作符和列表::刪除()

#ifndef TEST_H 
#define TEST_H 

#include <memory> 

template <class Type> 
bool operator==(const std::weak_ptr<Type>& wp1, const std::weak_ptr<Type>& wp2) 
{ 
std::shared_ptr<Type> sp1; 

if(!wp1.expired()) 
    sp1 = wp1.lock(); 

std::shared_ptr<Type> sp2; 

if(!wp2.expired()) 
    sp2 = wp2.lock(); 

return sp1 == sp2; 
} 

#endif 

Test.cpp的

#include "Test.h" 
#include <list> 


int main() 
{ 
typedef std::list< std::weak_ptr<int> > intList; 

std::shared_ptr<int> sp(new int(5)); 
std::weak_ptr<int> wp(sp); 

intList myList; 
myList.push_back(wp); 

myList.remove(wp); //Problem 
} 

程序不會編譯由於myList.remove() :

1> c:\ program files(x86)\ microsoft visual studio 10.0 \ VC \包括\列表(1194):錯誤C2678:二進制 '==':沒有操作員發現這需要 類型的左邊的操作數 '的std :: TR1 ::的weak_ptr < _Ty>'(或沒有可接受轉化率)1>
其中1> [1> _Ty = INT 1>]

但是你可以看到在Test.h以下定義:

bool operator==(const std::weak_ptr<Type>& wp1, const std::weak_ptr<Type>& wp2) 

什麼問題?

+0

不知道,但你可以嘗試定義布爾運算符==常量引用? – CharlesB 2012-04-15 21:53:15

+0

哎呀,我原來是這麼想的,忘了把它改回來。與const引用同樣的問題。 – user987280 2012-04-15 21:56:47

回答

6

運算符重載由argument-dependent lookup發現,並且它不是在命名空間std(參數類型的命名空間和表達的內std::list::remove的上下文中)定義了功能並不適用。

您應該使用remove_if應用自定義謂詞函數。通常,不要嘗試爲不能修改的庫中的類型定義運算符。

+0

我想你的意思是'std :: remove'和'std :: remove_if'。而且,你的鏈接似乎沒有任何意義。 – Fraser 2012-04-15 22:25:46

+0

@Fraser修好了,謝謝 – Potatoswatter 2012-04-15 22:35:14

+0

太好了,謝謝你的信息。我想完全避免這種情況,但我需要從weak_ptrs列表中刪除。在namespace std中定義operator ==會不好嗎?我只用remove_if和一個元素本身作爲參數的一元謂詞。我需要比較元素與我試圖刪除的指針。是否有可能用第二個參數調用謂詞? – user987280 2012-04-15 22:47:18