Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing mixed lists, issue with templates

Tags:

c++

templates

I am trying to implement a mixed list, so for example I would be able to do this:

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

And it's an exercise so isn't a valid solution to use other libraries like boost. This is the class with still few 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 manage the fact that using void pointers, I can't really cast the data pointed by it's real class.With dynamic_cast I should try all types (node, node, etc...) so it's not an acceptable solution. So for example if I want to print a series of nodes I can't do it:

int main(int argc, char** argv)
{
// for this example let's 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's 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++
}

The whole problem is that I don't what's the type of every element I iterate to. So next can be node or node or node, etc... but how to solve this problem? I would be able to know the type of every node but I just can't. How to implement mixed lists then?

like image 399
Ramy Al Zuhouri Avatar asked May 17 '26 17:05

Ramy Al Zuhouri


1 Answers

Since you don't know what kind of object you are storing I think the easiest way is to store a void pointer to an allocated copy of the object.

Next, you will need to store some kind of type tag along with the object. You could perhaps use the address of the type_info object returned by typeid.

I see some other problems which I don't know how to solve. To destroy the list you need a destructor for each element. Perhaps you can store the address of the destructor during element creation, when you know the type.

like image 129
Zan Lynx Avatar answered May 20 '26 07:05

Zan Lynx