模板部分专业化 - 任何现实世界的例子? [英] Template Partial Specialization - any real-world example?
问题描述
我在思考部分专业化
。虽然我理解这个想法,我还没有看到这种技术的任何真实世界的使用。 完全专业化
在 STL
中的许多地方使用,因此我没有问题。你能告诉我一个现实世界的例子,使用部分专业化
吗?如果示例是 STL
,那将是优越的!
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!
推荐答案
C ++ 0x带有 unique_ptr
,它替代了将被弃用的 auto_ptr
。
C++0x comes with unique_ptr
which is a replacement for auto_ptr
which is going to be deprecated.
如果对数组类型使用 unique_ptr
,则使用 delete []
来释放它,并提供
operator []
等。如果你使用非数组类型,它使用 delete
。这需要部分模板专门化,例如
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[]> { ... };
另一种用法(尽管非常有问题)是 std :: vector< bool ,Allocator>
。 bool专门化使用空间优化将bools包装成单独的位
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> { ... };
另一种用法是使用 std :: iterator_traits< T>
。迭代器需要定义嵌套的typedefs value_type
,引用
和其他的正确的类型(对于一个const迭代器,例如,code> reference 通常是 T const&
),因此算法可以使用它们进行工作。主模板依次使用迭代器类型的类型成员
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;
...
};
这篇关于模板部分专业化 - 任何现实世界的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!