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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)