C++模板中实例化和特化的区别 [英] Difference between instantiation and specialization in c++ templates

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆