简体   繁体   中英

Trying to create a templated linked list that contains different types of data

Hey i'm trying to create a linked list and i've ran into a dead end. I think my knowledge about templates is leaving me at a blank!

so i'm trying to create a linked list that contains an object , which contains a reference to some data and a reference to the previous object in the list.

so something like this:

template<class T>
class ClassHeader
{
    //-- Variables
    T* object;
    ClassHeader<T>* previousHeader;
};

I'm imagining it like this:

     Data______       Data_____
    |          |     |         |
    |__________|     |_________|
     ^                ^
     |                |
     |   Header       |   Header
    |Data*     |     |Data*    |
<---|Header*   |<----|Header*  |
    |          |     |         |
    |__________|     |_________|

And i'll be keeping a reference to the 'top' classheader of the list somewhere else. And then i plan on going down the list and accessing each 'object' as i go.

I can't figure out how to do this so far, as i would (as far as i can tell) need to know the the type of each previous 'object' before hand which is the information i'm trying to get!

Also each 'object' reference (data in the diagram) can be a completely different type.

Any help?

Perhaps this pattern from " Inheritance is the base class of evil " talk will help...

Corresponding source code can be found here - https://github.com/boostcon/cppnow_presentations_2012/blob/master/fri/value_semantics/value_semantics.cpp

Just take classes object_t and model_t from the code above and make object_t - the data type of your list. define helper and access methods as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM