template<>是什么意思?在C ++中带有空尖括号? [英] What is the meaning of template<> with empty angle brackets in C++?
问题描述
template<>
class A{
//some class data
};
我已经看过很多这种代码了。
在上面的代码中 template<>
有什么用?
在什么情况下我们需要强制使用它?
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?
推荐答案
template< ;>
告诉编译器遵循模板专业化,特别是完全专业化。通常, A类
必须看起来像这样:
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
}
现在,要使其过分杀伤,以下是部分专业化 >:
template<class T1, class T2>
class B{
};
template<class T1>
class B<T1, int>{
};
与完全专业化的工作方式相同,只是只要第二个模板参数都使用了专业化版本是 int
(例如, B< bool,int>
, B< YourType,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).
这篇关于template<>是什么意思?在C ++中带有空尖括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!