Jump to content
  • Advertisement
Sign in to follow this  
zomg

list of template items

This topic is 4580 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey all, I'm trying to make a list of template items. ex: template<class T> class item { T var; } . . . std::list<item> myList; This doesn't work, since the "item" must be specialized in the linked list declaration. I was wondering if someone could point me off in the right direction to a solution or work-around, as google hasn't been helpful. Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
Are you trying to create a list that can hold any object of any instantiation of item<T>? If so, that's not possible. If you derive your item<> class from a common base class you can store (smart) pointers to that base class in a list.

Share this post


Link to post
Share on other sites
I though that using a base class was right. So then it would be:

class base
{
}
template<class T> class item: public base
{
T var;
}

.
.
.

std::list<base*> myList;

But then how do you get to var? I tried a simple Get() that would be overridden, but that doesn't work since you can't change the signature to T Get(); from whatever it would be for the base class.

Share this post


Link to post
Share on other sites
Then you'd have to keep track of the type manually somehow and cast the pointer to the right type. This kind of thinking generally means that you shouldn't be trying to put different instantiations of your template type in the same container.

Share this post


Link to post
Share on other sites
templates are created at compile time and not at runtime.
everywhere you declare a type of the templated type you are infact creating a new class.
therefore no item<type> class can be seen as any other item<othertype> class because each class is unique and not related other than they came from the same place.

the 2 solutions to this are:

1. to not use templates at all and instead to use polymorphism and to use a base class to link all your classes together.

2. to declare the type of the item class in your list declaration (probably not what you want)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!