gpt4 book ai didi

c++ - 模板特化和实例化

转载 作者:可可西里 更新时间:2023-11-01 18:39:34 25 4
gpt4 key购买 nike

这些概念我有点不清楚。好吧,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.

如果我们有一个函数/变量/类模板,模板的实例化只是创建一个对象或函数。例如:

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 .

更新

假设您有以下类模板:

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>未在代码中的其他任何地方使用,类模板实例化为 charint .

显式模板特化

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

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>”。

关于c++ - 模板特化和实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28469604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com