运算符== 和列表::删除()

operator== and list::remove()

本文关键字:删除 列表 运算符      更新时间:2023-10-16

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 应用自定义谓词函数。通常,不要尝试为库中无法修改的类型定义运算符。