Reputation: 564
I have following code with error:
(Visual Studio error:)Error 5 error C2678: binary '!=' : no operator found which takes a left-hand operand of type '` Node' (or there is no acceptable conversion)
template <class C, class T>
C find2 ( C first , C last, T c )
{
//
while ( first != last && *first != c )
{
++first;
}
return first;
}
struct Node
{
Node(int a ,Node* b):val(a),next(b){};
int val;
Node* next;
};
template <class T>
struct node_wrap
{
T* ptr;
node_wrap ( T* p = 0 ) : ptr ( p ) {}
Node& operator*() const {return *ptr;}
Node* operator->() const {return ptr;}
node_wrap& operator++ () {ptr = ptr->next; return * this;}
node_wrap operator++ ( int ) {node_wrap tmp = *this; ++*this; return tmp;}
bool operator== ( const node_wrap& i ) const {return ptr == i.ptr;}
bool operator!= ( const node_wrap& i ) const {return ptr != i.ptr;}
};
bool operator== ( const Node& node, int n )
{
return node.val == n;
}
int main()
{
Node* node1=new Node(3,NULL);
Node* node2=new Node(4,NULL);
node1->next = node2;
find2 ( node_wrap<Node>(node1), node_wrap<Node>(), 3) ) ;
delete node1;
delete node2;
return 0;
}
what's wrong with this code?
Upvotes: 0
Views: 176
Reputation: 181735
Iterator
is of type node_wrap<Node>
, so *first
returns a Node
here:
while ( first != last && *first != c )
which has no !=
operator that compares it to the type of c
, which is int
. You probably meant:
while ( first != last && first->val != c )
I'd recommend this over the other approach of defining operator==
and operator!=
that compare Node
to int
, because these are fundamentally different types and should not be comparable to one another.
Upvotes: 3
Reputation: 110088
You are attempting to compare a Node
with an int
(this is done in the function find2
when performing *first != c
).
While you have provided an operator==
for comparing a Node
with an int
, you haven't provided an operator!=
to do the same. If you add one, this should work.
Upvotes: 2