模板专业化和实例化

Template specialization and instantiation

这些概念我有点不清楚。好吧,N4296::14.7 [temp.spec]:

很好地定义了模板实例化

The act of instantiating a function, a class, a member of a class template or a member template is referred to as template instantiation.

也就是说,如果我们有一个 function/variable/class 模板,模板的实例化只是创建一个对象或函数。例如:

template<typename T> class U{ };
U<int> a; //instantiation

但是 N4296:14.7.1 [temp.inst] 说(强调我的):

Unless a class template specialization has been explicitly instantiated (14.7.2) or explicitly specialized (14.7.3), the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program.

模板特化的实例化的定义是什么,而不仅仅是模板的实例化?

问题:

What's the definition of the instantiation of the template specialization, not just the instantiation of a template?

我的理解:

不存在模板实例化这样的东西。您总是实例化模板专业化。

如果你有:

template <typename T> struct Foo {};

Foo<int> foo;

您实例化了模板特化 Foo<int>,而不是模板 Foo

更新

假设您有以下 class 模板:

template <typename T> struct Foo
{
   static int a;
};

int getNext()
{
   static int n = 0;
   return ++n;
}

template <class T> int Foo<T>::a = getNext();

显式模板实例化

您可以使用以下方法创建 Foo<char>Foo<int> 的显式实例化:

template struct Foo<char>;
template struct Foo<int>;

即使 Foo<char>Foo<int> 未在代码中的其他任何地方使用,class 模板也会为 charint 实例化。

显式模板专业化

您可以使用以下方法创建 class 模板的显式特化:

template <> Foo<double> {};

使用Foo

现在,让我们看看Foo的用法。

Foo<int> f1;    // An explicit instantiation has already been created.
                // No need for any further code creation.

Foo<double> f2; // An explicit specialization has already been created.
                // No need for any further code creation.

Foo<long> f3;   // There is no explicit instantiation or explicit specialization
                // Code needs to be created for Foo<long>

           

第三种情况,Foo<long> f3; 触发创建模板特化 Foo<long>。我将短语 "class template specialization is implicitly instantiated" 解释为 "creation of Foo<long> from the class template。 ".

"Instantiating a template specialization"通常是指隐式实例化的过程:将特定的模板参数代入模板定义中,以获得实例化的class、函数等。实例化模板意味着实例化该模板的特化模板。通常,当我们在语言律师的上下文中谈论一些任意实例时,会使用不太精确的措辞。您还会发现表达式 "instantiation of a template",它是实例化特化的同义词。