Difference between instantiation and specialization in c++ templates(C++模板中实例化和特化的区别)
问题描述
C++ 模板上下文中的特化和实例化有什么区别.根据我目前阅读的内容,以下是我对特化和实例化的理解.
What is the difference between specialization and instantiation in context of C++ templates. From what I have read so far the following is what I have understood about specialization and instantiation.
template <typename T>
struct Struct
{
T x;
};
template<>
struct Struct <int> //specialization
{
//code
};
int main()
{
Struct <int> s; //specialized version comes into play
Struct <float> r; // Struct <float> is instantiated by the compiler as shown below
}
编译器对 Struct
的实例化
template <typename T=float>
struct Struct
{
float x;
}
我对模板实例化和特化的理解是否正确?
Is my understanding of template instantiation and specialization correct?
推荐答案
(隐式)实例化
这就是您所说的实例化(如问题中所述)
(Implicit) Instantiation
This is what you refer to as instantiation (as mentioned in the Question)
这是当您告诉编译器使用给定类型实例化模板时,如下所示:
This is when you tell the compiler to instantiate the template with given types, like this:
template Struct<char>; // used to control the PLACE where the template is inst-ed
(显式)专业化
这就是您所说的专业化(如问题中所述)
(Explicit) Specialization
This is what you refer to as specialization (as mentioned in the Question)
这是当您为类型的子集提供模板的替代定义时,如下所示:
This is when you give an alternative definition to a template for a subset of types, like this:
template<class T> class Struct<T*> {...} // partial specialization for pointers
这篇关于C++模板中实例化和特化的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++模板中实例化和特化的区别


基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01