问题:
模板特化的实例化的定义是什么,而不仅仅是模板的实例化?
我的理解:
没有模板实例化这样的东西。你总是实例化一个模板特化。
如果你有:
template <typename T> struct Foo {};
Foo<int> foo;
您已经实例化了模板特化Foo<int>,而不是模板Foo。
更新
假设你有以下类模板:
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> 没有在您的代码中的其他任何地方使用,类模板也会为char 和int 实例化。
显式模板特化
您可以使用以下方法创建类模板的显式特化:
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> 的创建。我将短语“类模板特化被隐式实例化”解释为“从类模板创建Foo<long>。”。