問(wèn)題描述
C++ 模板上下文中的特化和實(shí)例化有什么區(qū)別.根據(jù)我目前閱讀的內(nèi)容,以下是我對(duì)特化和實(shí)例化的理解.
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
}
編譯器對(duì) Struct
的實(shí)例化
template <typename T=float>
struct Struct
{
float x;
}
我對(duì)模板實(shí)例化和特化的理解是否正確?
Is my understanding of template instantiation and specialization correct?
推薦答案
(隱式)實(shí)例化
這就是您所說(shuō)的實(shí)例化(如問(wèn)題中所述)
(Implicit) Instantiation
This is what you refer to as instantiation (as mentioned in the Question)
這是當(dāng)您告訴編譯器使用給定類(lèi)型實(shí)例化模板時(shí),如下所示:
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
(顯式)專(zhuān)業(yè)化
這就是您所說(shuō)的專(zhuān)業(yè)化(如問(wèn)題中所述)
(Explicit) Specialization
This is what you refer to as specialization (as mentioned in the Question)
這是當(dāng)您為類(lèi)型的子集提供模板的替代定義時(shí),如下所示:
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
這篇關(guān)于C++模板中實(shí)例化和特化的區(qū)別的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!