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 

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 } 

The program will not compile due to myList.remove ():

1> c: \ program files (x86) \ Microsoft Visual Studio 10.0 \ vc \ include \ list (1194): error C2678: binary '==': an operator was not found that accepts a left operand of the type 'std :: tr1 :: weak_ptr <_Ty> '(or not acceptable conversion) 1>
with 1> [1> _Ty = int 1>]

But you can see the following in Test.h:

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

What is the problem?

+6
source share
1 answer

The operator overload was found to be dependent on the search argument , and your function is not applied because it is not defined in the std (the argument namespace is the types and expression context inside std::list::remove ).

You must use remove_if to apply a custom predicate function. In general, do not try to define operators for types within libraries that you cannot modify.

+6
source

Source: https://habr.com/ru/post/913269/


All Articles