問題描述
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++模板中實例化和特化的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!