Reputation:
I am trying to create a template class which contains a static list of objects which there is only one of. What i have so far works but it gives me a copy of "mylist" for each different type of class B parameter. How can i change it so that i get one "mylist" for all instantiations of class B regardless of template parameters?
This is what i have:
template <class T> class A {
...
};
template <class T> class B {
static list<A<T> > mylist;
...
};
template <class T> list< A<T> > B<T>::mylist;
Thanks in advance :)
Upvotes: 2
Views: 210
Reputation: 63946
How can change it so that i have only ONE copy
You can inherit from a common (non-templated) base class to ensure that there isn't an instance for every template instantiation.
... that contains any type?
That depends on your expectations. I'm going to assume from your example that "any type" means "any instantiation of template class A
".
Since those types could vary in size, you'll do best with holding pointers to the objects.
This is one example of a solution that would solve both those problems.
class ACommon {
// Put a common virtual interface here.
};
template <class T> class A : public ACommon {
};
class BCommon {
// You'll have a single, common static here.
static list<shared_ptr<ACommon> > mylist;
};
template <class T> class B : public BCommon{
};
Upvotes: 4
Reputation: 4708
You can not "just" have ANY type in a list, living side by side. Depending on what you expect to do with that list, and the objects in it, there are several things to do.
An alternative to Drew's solution would be:
You definitely need BCommon
if you want a single list for all instantiations. If you don't want to hide your A types behind an interface, you could use Boost::any or Boost::variant to hold your A objects.
Upvotes: 1