简体   繁体   English

具有不同实例化的静态模板类变量是否相同?

[英]Are static template class variables with different instantiations the same?

Say I have the class 说我上课了

template <typename T>
class MyClass
{
    static int myvar;
}

Now what will happen in the following assignments? 现在,以下任务将会发生什么?

MyClass<int>::myvar = 5;
MyClass<double>::myvar = 6;

What's going to happen according to the standard? 根据标准会发生什么? Am I gonna have two versions of MyClass::myvar or just one? 我会有两个版本的MyClass :: myvar还是只有一个?

Yes, there will be two variables with two different values. 是的,将有两个具有两个不同值的变量。 But that's because the two are completely unrelated classes . 但那是因为这两个是完全不相关的类 That's how templates work. 这就是模板的工作原理。 Don't think of them as classes, but rather as a set of rules after which classes are built. 不要将它们视为类,而应将其视为构建类之后的一组规则。

Since the OP specifically requested a quote from the standard, here is my answer which includes the relevant quote from the standard. 由于OP特别要求标准引用,这里是我的答案,其中包括标准的相关引用。

Each specialization will have it's own copy of myvar which makes sense since each is it's own distinct class . 每个专业都将拥有它自己的myvar副本,这是有道理的,因为每个都是它自己独特的 The C++ draft standard in section 14.7 Template instantiation and specialization paragraph 6 says( emphasis mine ): 14.7节中的C ++草案标准模板实例化和专业化6段说( 强调我的 ):

Each class template specialization instantiated from a template has its own copy of any static members . 从模板实例化的每个类模板特化都有自己的任何静态成员的副本

  [ Example: template<class T> class X { static T s; }; template<class T> T X<T>::s = 0; X<int> aa; X<char*> bb; 

X has a static member s of type int and X has a static member s of type char*. X有一个int类型的静态成员,X有一个char *类型的静态成员。 —end example ] - 末端的例子]

A completely 'new class' is instantiated from the template for 'each typename'. 从“每个类型名称”的模板中实例化一个完全“新类”。 And since static member are tied to class, each of these classes have their own copies of the static variable. 由于静态成员与类绑定,因此每个类都有自己的静态变量副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM