C++静态模板成员,每种模板类型一个实例?

发布于 2024-08-20 06:09:11 字数 358 浏览 4 评论 0原文

通常,一个类的静态成员/对象对于具有静态成员/对象的类的每个实例是相同的。无论如何,如果静态对象是模板类的一部分并且还依赖于模板参数怎么办?例如,像这样:

template<class T>
class A{
public:
  static myObject<T> obj;
}

如果我将 A 的一个对象转换为 int,将另一个对象转换为 float,我猜会有两个 obj ,每种类型一个?

如果我创建 A 的多个对象作为 int 类型和多个 float ,它仍然是两个 obj 实例,因为我只使用两种不同的类型?

Usually static members/objects of one class are the same for each instance of the class having the static member/object. Anyways what about if the static object is part of a template class and also depends on the template argument? For example, like this:

template<class T>
class A{
public:
  static myObject<T> obj;
}

If I would cast one object of A as int and another one as float, I guess there would be two obj, one for each type?

If I would create multiple objects of A as type int and multiple floats, would it still be two obj instances, since I am only using two different types?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

青衫负雪 2024-08-27 06:09:12

每个不同的模板初始化的静态成员都是不同的。这是因为每个模板初始化都是一个不同的类,由编译器第一次遇到模板的特定初始化时生成。

以下代码显示了静态成员变量不同的事实

#include <iostream>

template <class T> class Foo {
  public:
    static int bar;
};

template <class T>
int Foo<T>::bar;

int main(int argc, char* argv[]) {
  Foo<int>::bar = 1;
  Foo<char>::bar = 2;

  std::cout << Foo<int>::bar  << "," << Foo<char>::bar;
}

1,2

Static members are different for each diffrent template initialization. This is because each template initialization is a different class that is generated by the compiler the first time it encounters that specific initialization of the template.

The fact that static member variables are different is shown by this code:

#include <iostream>

template <class T> class Foo {
  public:
    static int bar;
};

template <class T>
int Foo<T>::bar;

int main(int argc, char* argv[]) {
  Foo<int>::bar = 1;
  Foo<char>::bar = 2;

  std::cout << Foo<int>::bar  << "," << Foo<char>::bar;
}

Which results in

1,2
泪之魂 2024-08-27 06:09:12

AA 是两种完全不同的类型,您无法在它们之间安全地进行转换。不过,A 的两个实例将共享相同的静态 myObject。

A<int> and A<float> are two entirely different types, you cannot cast between them safely. Two instances of A<int> will share the same static myObject though.

怀里藏娇 2024-08-27 06:09:12

有多少类就有多少静态成员变量,这同样适用于模板。模板类的每个单独实例化仅创建一个静态成员变量。这些模板类的对象数量是无关紧要的。

There are as many static member variables as there are classes and this applies equally to templates. Each separate instantiation of a template class creates only one static member variable. The number of objects of those templated classes is irrelevant.

错爱 2024-08-27 06:09:12

在 C++ 中,模板实际上是类的副本。我认为在您的示例中,每个模板实例都有一个静态实例。

In C++ templates are actually copies of classes. I think in your example there would be one static instance per template instance.

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