Template Partial Specialization - any real-world example?

老子叫甜甜 提交于 2019-12-05 13:49:50

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;
  ...
};

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.

Taken from MSDN (Partial Specialization of Class Templates (C++))

// partial_specialization_of_class_templates.cpp
template <class T> struct PTS {
   enum {
      IsPointer = 0,
      IsPointerToDataMember = 0
   };
};

template <class T> struct PTS<T*> {
   enum {
      IsPointer = 1,
      IsPointerToDataMember = 0
   };
};

template <class T, class U> struct PTS<T U::*> {
   enum {
      IsPointer = 0,
      IsPointerToDataMember = 1
   };
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!