Search code examples
c++templatescastingcircular-list

cannot convert 'clist<int>::node*' to 'clist<char>::node*' in assignment


Here I'm making a circular linked list ( template <class t> class clist; ) with a member function, concat () used to concatenate one list at the end of the other. The problem lies in this function. Now when I'm concatenating two clist with same template parameters (let say both be clist<int>) then function works fine, but as soon as I try concatenate two clists ( clist <int> c1 and clist <char> c2) then I need to do some casting in the function concat, and as I dont know much about templates, I cudnt actually figure out how to do that.

So the problem precisely is with the last second line of the program below. I have clist <int> c1 whose member function concat is being called, and clist <char> c2 which is being concatenated at the end of c1.

template <class t>
class clist
{
    struct node
    {
    t data;
    node* next;
    node (const t& x=0, node* nxt=0): data(x), next(nxt) { }
    };

    typedef node* NPTR;

    public:

    NPTR ptr;

    template <class r>
    void concat ( clist <r> & );

    // other functions like push, pop etc. to form the clist

    clist () : ptr(0) { }
};

template <class t>
template <class r>
void clist<t> :: concat ( clist <r>& c2 )
{
    // ptr is pointer to a certain node in the list through which the list is
    // accessedand is zero initially.

    if ( c2.ptr == 0 ) return;
    if ( ptr == 0 ) ptr = (NPTR) c2.ptr;
    else
    {
    NPTR p = ptr->next;
    ptr->next = (NPTR) c2.ptr->next;
    c2.ptr->next = ( ??? ) p ;
    ptr = (NPTR)c2.ptr;
}

Whatever I try it still shows the error cannot convert 'clist<int>::node*' to 'clist<char>::node*' in assignment.

Can somebody please tell what is the proper way of casting here ?


Solution

  • The cast is actually saving you from making a heterogeneous list. What you seem to be trying to do is to concatenate two lists - one with int and one with char. Now conceptually that might seem reasonable but the structure of an int node and a char node are too different.

    The only way this could make sense is if you copied the second list into a clist of ints and then concatenated.