首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >模板/泛型类中的非常数静态成员- c++与c#

模板/泛型类中的非常数静态成员- c++与c#
EN

Stack Overflow用户
提问于 2013-06-16 18:05:09
回答 1查看 640关注 0票数 1

在c#中,静态成员对于每个泛型类都是唯一的,如下例所示

代码语言:javascript
运行
复制
using System;

//A generic class
public class GenTest<T>
{
  //A static variable - will be created for each type on refraction
  static CountedInstances OnePerType = new CountedInstances();

  //a data member
  private T mT;

  //simple constructor
  public GenTest(T pT)
  {
    mT = pT;
  }
}

//a class
public class CountedInstances
{
  //Static variable - this will be incremented once per instance
  public static int Counter;

  //simple constructor
  public CountedInstances()
  {
    //increase counter by one during object instantiation
    CountedInstances.Counter++;
    Console.WriteLine(Counter);
  }
}

public class staticTest {
  static void Main(string[] args) {
    //main code entry point
    //at the end of execution, CountedInstances{{Not a typo|.}}Counter = 2
    GenTest<int> g1 = new GenTest<int>(1);
    GenTest<int> g11 = new GenTest<int>(11);
    GenTest<int> g111 = new GenTest<int>(111);
    GenTest<double> g2 = new GenTest<double>(1.0);
  }
}

来自http://en.wikipedia.org/wiki/Generic_programming

那c++呢?我试着自己去检查,但是翻译成c++似乎忽略了静态成员。

代码语言:javascript
运行
复制
#include <iostream>
using namespace std;

class CountedInstances {
public:
  static int Counter;
  CountedInstances() {
    Counter++;
    cout << Counter << endl;
  }
};

int CountedInstances::Counter = 0;

template<class T> class GenTest {
  static CountedInstances OnePerType;
  T mT;
public:
  GenTest(T pT) {
    mT = pT;
  }
};

template<class T> CountedInstances GenTest<T>::OnePerType = CountedInstances();

int main() {
  GenTest<int> g1(1);
  GenTest<int> g11(11);
  GenTest<int> g111(111);
  GenTest<double> g2(1.0);
  cout << CountedInstances::Counter << endl;
  //CountedInstances c1;
  //CountedInstances c2;
}

在这个answer中,我可以看到在c++中,静态成员对于每个专门化都是唯一的,然而,我的代码似乎是合法的,但是静态成员OnePerType被忽略了。

我认为对于每个GenTest<>,计数器都会被打印出来,只有当我在注释中创建CountedInstances类型的对象时才会发生什么。为什么会这样呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-16 19:03:23

来自IBM C++ compilers reference (重点是我的):

如果编译器隐式实例化包含静态成员的类模板,则这些静态成员是隐式实例化的。只有当编译器需要静态成员的定义时,编译器才会实例化该静态成员。

因此,为了强制编译器有效地实例化GenTest<int>::OnePerTypeGenTest<double>::OnePerType,您必须以某种方式引用它们。例如,您可以在构造函数中添加(void)&OnePerType; (实时示例:http://ideone.com/CWNr7U)。

编辑:多亏了chris.schuette,这里引用了C++标准(检查N3337),§14.7.1 (强调我的):

1 (...)类模板专门化的隐式实例化导致类成员函数、成员类、作用域成员枚举、静态数据成员和成员模板的声明的隐式实例化,而不是定义或默认参数的隐式实例化;(...)

8类模板的隐式实例化不会导致该类的任何静态数据成员被隐式实例化。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17132114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档