Introducing Mixed Lists, Template Edition

I am trying to implement a mixed list, so for example, I could do this:

mylist* l= new mylist();
l.push_back<int> (4);
l.push_back<string> ("hello");

And this exercise, therefore, is not a valid solution for using other libraries, such as boost. This is a class with a few more methods:

template <class T>
class node
{
private:

    void* next;
    void* prev;
    T data;

public:

    node(T data)
    {
        this->data=data;
    }

    template <class R>
    void link_to (node<R>& other)
    {
        next=&other;
        other.prev=this;
    }

};

Because I don’t know how to control the fact that with the help of void pointers I cannot distinguish the data pointed to by this class. With dynamic_cast, I have to try all types (node, node, etc.) ....), so this is not an acceptable solution. So, for example, if I want to print a series of nodes, I cannot do this:

int main(int argc, char** argv)
{
// for this example let suppose that node fields were public
    node<int> a(1),c(2);
    node<std::string> b; 
    a.linkTo(b);
    b.linkTo(c);
    std::cout << a.data;  // this is ok but I need to print also other nodes
// let suppose that b and c were unreachable and that I want to reach them
// by iterating into the list
    void* ptr=a.next; //public field
    cout << ptr->data; //can't do that in C++
}

, , . , node node node ..... ? node, . ?

+3
1

, , , - void .

- . , type_info, typeid.

, , . , . , , .

+2

All Articles