2012-04-15 39 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