C++0x 附带unique_ptr
这是替代品auto_ptr
它将被弃用。
如果你使用unique_ptr
对于数组类型,它使用delete[]
释放它,并提供operator[]
等等。如果您将它与非数组类型一起使用,它会使用delete
。这需要部分模板专业化,例如
template<typename T>
struct my_unique_ptr { ... };
template<typename T>
struct my_unique_ptr<T[]> { ... };
另一个用途(尽管非常值得怀疑)是std::vector<bool, Allocator>
在标准库中。 bool 特化使用空间优化将 bool 打包成单独的位
template<typename T, typename Allocator = std::allocator<T> >
struct vector { ... };
template<typename Allocator>
struct vector<bool, Allocator> { ... };
还有一个用途是std::iterator_traits<T>
。需要迭代器来定义嵌套的 typedefvalue_type
, reference
和其他正确的类型(对于常量迭代器,reference
通常会是T const&
,例如),因此算法可以使用它们来完成工作。主模板依次使用迭代器类型的类型成员
template<typename T>
struct iterator_traits {
typedef typename T::value_type value_type;
...
};
对于指针来说,这当然行不通。他们有部分专业化
template<typename T>
struct iterator_traits<T*> {
typedef T value_type;
...
};