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
440 views
in Technique[技术] by (71.8m points)

What is the meaning of template<> with empty angle brackets in C++?

template<>
class A{
//some class data
};

I have seen this kind of code many times. what is the use of template<> in the above code? And what are the cases where we need mandate the use of it?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

template<> tells the compiler that a template specialization follows, specifically a full specialization. Normally, class A would have to look something like this:

template<class T>
class A{
  // general implementation
};

template<>
class A<int>{
  // special implementation for ints
};

Now, whenever A<int> is used, the specialized version is used. You can also use it to specialize functions:

template<class T>
void foo(T t){
  // general
}

template<>
void foo<int>(int i){
  // for ints
}

// doesn't actually need the <int>
// as the specialization can be deduced from the parameter type
template<>
void foo(int i){
  // also valid
}

Normally though, you shouldn't specialize functions, as simple overloads are generally considered superior:

void foo(int i){
  // better
}

And now, to make it overkill, the following is a partial specialization:

template<class T1, class T2>
class B{
};

template<class T1>
class B<T1, int>{
};

Works the same way as a full specialization, just that the specialized version is used whenever the second template parameter is an int (e.g., B<bool,int>, B<YourType,int>, etc).


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

...