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.
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.
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.
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
.
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:
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)boost::variant
, it's statically checked so you have reasonable guaranteesboost::any
under the coversThe 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
.