By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,260 Members | 1,233 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,260 IT Pros & Developers. It's quick & easy.

containers of templates

P: n/a
Hi,
I want to create a vector of templates, but I've come across a problem....
Here is a trimmed version of my template definition:
template<class T>
class variant
{
public:

variant(T val)
{
_val = val;
}
private:
T _val;
};
i want to create a vector of these, where T can be various types,
however when i create the vector, i need to specify a single type, eg:

std::vector<variant<XXX>> vars;

where XXX is a specific type.

Someone recommended i make the template extend a superclass, but im not
sure how exactly that would work.
Does that make sense?
Is there a way round this?
Thanks

Andrew Bullock
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Andrew Bullock wrote:
I want to create a vector of templates, but I've come across a
problem....
A container of templates is itself a template. If you need to have
an object of that type, you'd have to _specialise_ it (explicitly or
implicitly).
Here is a trimmed version of my template definition:
template<class T>
class variant
{
public:

variant(T val)
{
_val = val;
}
private:
T _val;
};
i want to create a vector of these, where T can be various types,
however when i create the vector, i need to specify a single type, eg:

std::vector<variant<XXX>> vars;

where XXX is a specific type.
Yep.
Someone recommended i make the template extend a superclass, but im
not sure how exactly that would work.
If you have a common base _class_ of all 'variant<>', you could store
pointers to those in your vector, and treat them polymorphically...
Does that make sense?
Yes, but...
Is there a way round this?


Nope.

You might want to look at "heterogenous container" on the Web.

V
Jul 23 '05 #2

P: n/a
Andrew Bullock wrote:
Hi,
I want to create a vector of templates, but I've come across a problem....


Victor already addressed your questions, but note that there's a
perfectly good reason why this can't work. Think of the havoc it would
wreak upon a vector if each contained element was a different size
(inevitable since your variant object includes a T object). Allocating
space for more than one object at a time would be impossible, random
access iterators would be nearly useless because you wouldn't know how
far ahead in memory to jump, etc.
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.