tags:

views:

117

answers:

3

Is there any hack I could use to do this:

template <class TYPE>
class Hello
{
     TYPE _var;
};

I would like a way to store

Hello<int> intHello and Hello<char*> charHello

into the same Container such as a Queue / List.

+6  A: 

No, because they are different and completely unrelated types.

You can, however, use inheritance and smart pointers:

class HelloBase 
{
public:
    virtual ~HelloBase(); 
}

template <class TYPE>
class Hello : public HelloBase
{
    TYPE _var;
{

std::vector<boost::shared_ptr<HelloBase> > v;

shared_ptr may be supported by your implementation either in the std::tr1 or std namespace; you'd have to check.

James McNellis
+5  A: 

Yes, sort of -- but you probably don't want to. Even though they start from the same template, Hello<int> and Hello<char *> are completely separate and unrelated types. A collection that includes both is heterogeneous, with all the problems that entails.

If you insist on doing this anyway, to do it reasonably cleanly, you'd typically create something like a queue/list of Boost::any.

Jerry Coffin
+2  A: 

First of all, the real question: what are you trying to achieve (at a higher level) ?

Now, for this peculiar question there is a number of alternative. Containers cannot store heterogeneous data, so you can:

  • give all Hello<T> a common base class and add virtual methods, then use pointers, take care of memory ownership (unique_ptr or boost::ptr_list would be great)
  • if there is a precise set of types, use boost::variant, it's statically checked so you have reasonable guarantees
  • else you should consider wrapping it into a storage class which would use boost::any under the covers

The common base class is the usual approach in this situation. If there is no reason to have polymorphism, then use preferably variant and if nothing else any.

Matthieu M.
I think this is a very good answer. I was missing variant on the other ones. To it seems like the preferred way.
Johannes Schaub - litb