C++模板中实例化和特化的区别

2023-03-10C/C++开发问题
1

本文介绍了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++模板中实例化和特化的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6