运算符== 和列表::删除()
operator== and list::remove()
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
测试.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\include\list(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)
问题出在哪里?
运算符
重载是通过与参数相关的查找找到的,并且您的函数不适用,因为它未在命名空间std
(参数类型的命名空间以及std::list::remove
中表达式的上下文)中定义。
应使用 remove_if
应用自定义谓词函数。通常,不要尝试为库中无法修改的类型定义运算符。
相关文章:
- C++如何通过用户输入删除列表元素
- 删除列表中的第n个元素
- 删除列表 c++ 中的最后 3 个元素
- 链表.如何删除列表中的第一个节点?
- 在 c++ 中删除列表中的重复元素
- 如何删除列表中的动态分配类对象<T>?
- 无法在C 中删除列表元素
- 使用共享_ptr删除列表中的对象
- 删除列表向量中的元素并显示当前列表
- 如何在C++中删除列表中的某些元素
- 当删除列表元素时,在迭代器结束时会发生什么
- 删除列表中的对象后,为什么可以访问该对象的成员变量
- 如何删除列表中的字符串
- C++迭代时删除列表成员:标准解决方案不起作用
- 迭代时删除列表中的最后一个元素会导致错误
- 如何正确删除列表中的对象
- 在 c++ 中删除列表
- 当链表节点是用"new"构造时,如何删除列表?
- 从另一个 c++ 中删除 1 列表中出现的所有元素
- 删除列表 CPP 中的重复项