将静态变量与模板一起使用
我正在尝试创建一个模板类,其中包含只有一个对象的静态列表。到目前为止我所拥有的有效,但它为我提供了每种不同类型的 B 类参数的“mylist”副本。我如何更改它,以便无论模板参数如何,我都能为 B 类的所有实例获得一个“mylist”?
这就是我所拥有的:
template <class T> class A {
...
};
template <class T> class B {
static list<A<T> > mylist;
...
};
template <class T> list< A<T> > B<T>::mylist;
提前致谢:)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从公共(非模板化)基类继承,以确保每个模板实例化都没有一个实例。
这取决于您的期望。我将从您的示例中假设“任何类型”意味着“模板类
A
的任何实例化”。由于这些类型的大小可能会有所不同,因此最好保留指向对象的指针。
这是解决这两个问题的一个示例。
You can inherit from a common (non-templated) base class to ensure that there isn't an instance for every template instantiation.
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.
您不能“仅”在列表中包含任何类型,并排生活。根据您希望对该列表及其中的对象执行的操作,有几件事情要做。
德鲁解决方案的替代方案是:
如果您想要所有实例化的单个列表,您肯定需要
BCommon
。如果您不想将 A 类型隐藏在接口后面,您可以使用 Boost::any 或 Boost::variant 来保存 A 对象。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.