Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Partial Specialization - any real-world example?

I am pondering about partial specialization. While I understand the idea, I haven't seen any real-world usage of this technique. Full specialization is used in many places in STL so I don't have a problem with that. Could you educate me about a real-world example where partial specialization is used? If the example is in STL that would be superior!

like image 210
Khaled Alshaya Avatar asked Dec 02 '22 07:12

Khaled Alshaya


2 Answers

C++0x comes with unique_ptr which is a replacement for auto_ptr which is going to be deprecated.

If you use unique_ptr with an array type, it uses delete[] to free it, and to provide operator[] etc. If you use it with a non-array type, it uses delete. This needs partial template specialization like

template<typename T>
struct my_unique_ptr { ... };

template<typename T>
struct my_unique_ptr<T[]> { ... };

Another use (although a very questionable) is std::vector<bool, Allocator> in the standard library. The bool specialization uses a space optimization to pack bools into individual bits

template<typename T, typename Allocator = std::allocator<T> >
struct vector { ... };

template<typename Allocator>
struct vector<bool, Allocator> { ... };

Yet another use is with std::iterator_traits<T>. Iterators are required to define the nested typedefs value_type, reference and others to the correct types (for a const iterator, reference would usually be T const&, for example) so algorithms may use them for their work. The primary template uses type-members of the iterator type in turn

template<typename T>
struct iterator_traits { 
  typedef typename T::value_type value_type; 
  ...
};

For pointers, that of course doesn't work. There is a partial specialization for them

template<typename T>
struct iterator_traits<T*> {
  typedef T value_type;
  ...
};
like image 157
Johannes Schaub - litb Avatar answered Dec 04 '22 14:12

Johannes Schaub - litb


In some stl implementations collections like std::vector and std::list use partial template specialization to reduce the amount of code generated for collections of pointers.

Each instantiation of a template for a type T creates new code. However pointer types are effectively all the same so generating new code for every type is a waste. This can be reduced by implementing the private part of pointer collections with void pointers and then casting these to the appropriate type in the public interface. This greatly reduces the code generated for pointer collections.

I think this is covered in Effective STL.

like image 39
iain Avatar answered Dec 04 '22 12:12

iain