Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Any way to store different templated object into the same container

Tags:

c++

templates

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.

like image 303
JP. Avatar asked May 04 '10 13:05

JP.


3 Answers

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.

like image 116
James McNellis Avatar answered Nov 15 '22 06:11

James McNellis


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.

like image 26
Jerry Coffin Avatar answered Nov 15 '22 06:11

Jerry Coffin


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.

like image 29
Matthieu M. Avatar answered Nov 15 '22 06:11

Matthieu M.