问题描述
这种代码我见过很多次了.上面代码中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<>
告诉编译器遵循模板特化,特别是完全特化.通常,class A
应该是这样的:
template<>
tells the compiler that a template specialization follows, specifically a full specialization. Normally, class A
would have to look something like this:
现在,每当使用 A
时,都会使用专用版本.你也可以用它来专门化函数:
Now, whenever A<int>
is used, the specialized version is used. You can also use it to specialize functions:
通常情况下,你不应该专门化函数,因为简单的重载通常被认为是优越的:
Normally though, you shouldn't specialize functions, as simple overloads are generally considered superior:
<小时>
现在,为了让它显得矫枉过正,以下是一个部分专业化:
与完全特化的工作方式相同,只是当第二个模板参数是 int
(例如,B
、B
等).
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).
这篇关于模板是什么意思?在 C++ 中使用空尖括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!