Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...