Chebz
Chebz

Reputation: 1395

error C2440: '<function-style-cast>' : cannot convert from 'LinkedList<int>::Node *' to 'LinkedListIterator<const T>'

I am trying to implement linked list iterator and getting compile error. In my test code T is int. When I try to call iterator constructor, it doesn't see the option where Node is passed as an argument.

Here is the code:

template <typename T>
class LinkedListIterator
{
    typedef typename LinkedList<T>::Node Node;
    ...

    LinkedListIterator(Node* p) : p(p) {}
    LinkedListIterator(const LinkedListIterator& other) : p(other.p) {}
    LinkedListIterator& operator=(LinkedListIterator other) { std::swap(p, other.p); return *this; }
    ...
};

template <typename T>
class LinkedList
{
    struct Node ...

    friend class LinkedListIterator<T>;
    friend class LinkedListIterator<const T>;

    ...

    typedef LinkedListIterator<T> iterator;
    typedef LinkedListIterator<const T> const_iterator;

    ...

    const_iterator begin() const //where error happens
    {
        return const_iterator(head->next);
    }
...

};

Upvotes: 0

Views: 14640

Answers (1)

user743382
user743382

Reputation:

In your code, you're attempting to construct LinkedList<int>::const_iterator, which is LinkedListIterator<const int>. LinkedListIterator<const int> has two constructors allowing conversions: one copy constructor that I'll ignore, and one from LinkedListIterator<const int>::Node *. LinkedListIterator<const int>::Node * is LinkedList<const int>::Node *. But you don't have a LinkedList<const int>::Node *, you have a LinkedList<int>::Node *. That's a completely different type, so the compiler is right to reject the conversion.

If you want to add any sort of inheritance relation between LinkedList<int> and LinkedList<const int> (I don't know if it makes sense), you could add a partial specialisation and let LinkedList<const T>::Node relate to LinkedList<T>::Node, but without any special work on your part, a compiler error is all you're going to get.

Upvotes: 2

Related Questions