Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

Difference between instantiation and specialization in c++ templates

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

}

Instantiation of Struct <float> by the compiler

template <typename T=float>
struct Struct
{
    float x;
}

Is my understanding of template instantiation and specialization correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(Implicit) Instantiation

This is what you refer to as instantiation (as mentioned in the Question)

Explicit Instantiation

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)

Partial Specialization

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...