将静态变量与模板一起使用

发布于 2025-01-02 08:35:23 字数 389 浏览 1 评论 0原文

我正在尝试创建一个模板类,其中包含只有一个对象的静态列表。到目前为止我所拥有的有效,但它为我提供了每种不同类型的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

动听の歌 2025-01-09 08:35:23

如何更改它以便我只有一份副本

您可以从公共(非模板化)基类继承,以确保每个模板实例化都没有一个实例。

...包含任何类型?

这取决于您的期望。我将从您的示例中假设“任何类型”意味着“模板类 A 的任何实例化”。

由于这些类型的大小可能会有所不同,因此最好保留指向对象的指针。

这是解决这两个问题的一个示例

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{

};

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{

};
幸福还没到 2025-01-09 08:35:23

您不能“仅”在列表中包含任何类型,并排生活。根据您希望对该列表及其中的对象执行的操作,有几件事情要做。

德鲁解决方案的替代方案是:
如果您想要所有实例化的单个列表,您肯定需要 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文