为什么要用模板<>没有专业化?

发布于 2024-08-22 15:36:44 字数 404 浏览 1 评论 0 原文

我正在阅读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<>部分是为了避免类重复吗?

I was reading the STL source code (which turned out to be both fun and very useful), and I came across this kind of thing

//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>

Is the template<> part added to avoid class duplication?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若相惜即相离 2024-08-29 15:36:44

这就是专业化。例如:

template <typename T>
struct is_void
{
    static const bool value = false;
};

此模板将 is_void::value 对于 any 类型设置为 false,这显然是不正确的。您可以做的是使用此语法来表示“我自己填写 T,并专门化”:

template <> // I'm gonna make a type specifically
struct is_void<void> // and that type is void
{
    static const bool value = true; // and now I can change it however I want
};

现在 is_void::valuefalse,除非 <代码>T是void。然后编译器选择更专业的版本,我们得到true

因此,就您而言,它具有 auto_ptr 的通用实现。但该实现存在 void 问题。具体来说,它不能被取消引用,因为它没有与之关联的类型。

因此,我们可以做的是专门化 auto_ptrvoid 变体来删除这些函数。

That's specialization. For example:

template <typename T>
struct is_void
{
    static const bool value = false;
};

This template would have is_void<T>::value as false 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":

template <> // I'm gonna make a type specifically
struct is_void<void> // and that type is void
{
    static const bool value = true; // and now I can change it however I want
};

Now is_void<T>::value is false except when T is void. Then the compiler chooses the more specialized version, and we get true.

So, in your case, it has a generic implementation of auto_ptr. But that implementation has a problem with void. Specifically, it cannot be dereferenced, since it has no type associated with it.

So what we can do is specialize the void variant of auto_ptr to remove those functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文