开发者

Why use template<> without specialization?

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 aut开发者_开发百科o_ptr

//Question is about this:
template<>
    class auto_ptr<void>

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜