What is the reason for ambiguity in the function call in the code below?
I get that there are two viable functions here, as the compiler tells in the ERROR
message (shown below at the end)
1) candidate: operator==(Base*, Base*)
-> requires user defined conversion from SmartPtr
to Base*
for the first parameter
-> requires Derived*
to Base*
implicit (?) conversion
2)candidate: bool operator==(const SmartPtr&, const Base*)
-> requires addition of top level const (exact match) for first parameter
-> requires Derived*
to Base*
implicit (?) conversion
From above it is quite clear that operator==
defined inside SmartPtr
is the better match (considering the first parameter and second one being same)
CODE:
#include <iostream>
using namespace std;
template<class T> class SmartPtr
{
public:
operator T*() { return pointee__;}
inline friend bool operator==(const SmartPtr& lhs, const T* rhs){
return lhs.pointee__ == rhs;
}
private:
T* pointee__;
};
struct Base{};
class Derived:public Base{};
int main()
{
SmartPtr<Base> sp;
Derived * dp;
cout<<"Hello World"<< (sp==dp);
return 0;
}
ERROR:
main.cpp: In function ‘int main()’:
main.cpp:38:30: error: ambiguous overload for ‘operator==’ (operand types are ‘SmartPtr’ and ‘Derived*’)
cout<<"Hello World"<< (sp==dp);
~~^~~~
main.cpp:38:30: note: candidate: operator==(Base*, Base*)
main.cpp:19:24: note: candidate: bool operator==(const SmartPtr&, const Base*)
inline friend bool operator==(const SmartPtr& lhs, const T* rhs){
^~~~~~~~
Thanks!
Aucun commentaire:
Enregistrer un commentaire