containers of templates

A

Andrew Bullock

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
 
V

Victor Bazarov

Andrew said:
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.

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
 
M

Mark P

Andrew said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Variadic templates std::tuple 2
templates 10
Templates and g++ 4
Templates question 2
workaround for auto_ptr<> in STL containers? 8
Specialized Templates 3
Recursive templates 3
Templates 5

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,664
Latest member
RoseannBow

Latest Threads

Top