Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use template<> without specialization?

Tags:

c++

templates

stl

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?

like image 638
Tom Avatar asked Dec 11 '25 07:12

Tom


1 Answers

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.

like image 62
GManNickG Avatar answered Dec 12 '25 21:12

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!