为什么要用模板<>没有专业化?
我正在阅读STL源代码(结果证明它既有趣又非常有用),我遇到了这种事情:
//file backwards/auto_ptr.h, but also found on many others.
template<typename _Tp>
class auto_ptr
//Question is about this:
template<>
class auto_ptr<void>
添加template<>
部分是为了避免类重复吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是专业化。例如:
此模板将
is_void::value
对于 any 类型设置为false
,这显然是不正确的。您可以做的是使用此语法来表示“我自己填写 T,并专门化”:现在
is_void::value
为false
,除非 <代码>T是void
。然后编译器选择更专业的版本,我们得到true
。因此,就您而言,它具有
auto_ptr
的通用实现。但该实现存在void
问题。具体来说,它不能被取消引用,因为它没有与之关联的类型。因此,我们可以做的是专门化
auto_ptr
的void
变体来删除这些函数。That's specialization. For example:
This template would have
is_void<T>::value
asfalse
for any type, which is obviously incorrect. What you can do is use this syntax to say "I'm filling in T myself, and specializing":Now
is_void<T>::value
isfalse
except whenT
isvoid
. Then the compiler chooses the more specialized version, and we gettrue
.So, in your case, it has a generic implementation of
auto_ptr
. But that implementation has a problem withvoid
. Specifically, it cannot be dereferenced, since it has no type associated with it.So what we can do is specialize the
void
variant ofauto_ptr
to remove those functions.