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++模板中实例化和特化的区别
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01