模板部分专业化 - 有现实世界的例子吗?
我正在考虑部分专业化
。虽然我理解这个想法,但我还没有看到这种技术在现实世界中的任何用法。 完全专业化
在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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在某些 stl 实现中,
std::vector
和std::list
等集合使用部分模板专门化来减少为指针集合生成的代码量。类型 T 模板的每次实例化都会创建新代码。然而,指针类型实际上都是相同的,因此为每种类型生成新代码是一种浪费。通过使用 void 指针实现指针集合的私有部分,然后将它们转换为公共接口中的适当类型,可以减少这种情况。这大大减少了为指针集合生成的代码。
我认为Effective STL 中已经涵盖了这一点。
In some stl implementations collections like
std::vector
andstd::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.
摘自 MSDN(类模板的部分特化 (C++))
Taken from MSDN (Partial Specialization of Class Templates (C++))
C++0x 附带了
unique_ptr
,它是即将被弃用的auto_ptr
的替代品。如果您将
unique_ptr
与数组类型一起使用,它会使用delete[]
来释放它,并提供operator[]
等。如果您使用对于非数组类型,它使用delete
。这需要部分模板专门化,就像标准库中的另一个用途(尽管非常有问题)是
std::vector
一样。 bool 特化使用空间优化将 bool 打包到各个位中。另一个用途是与
std::iterator_traits
一起使用。迭代器需要将嵌套 typedefsvalue_type
、reference
和其他类型定义为正确的类型(对于 const 迭代器,reference
通常为T const&
,例如),因此算法可以使用它们来完成工作。主模板依次使用迭代器类型的类型成员作为指针,这当然不起作用。他们有部分专业化
C++0x comes with
unique_ptr
which is a replacement forauto_ptr
which is going to be deprecated.If you use
unique_ptr
with an array type, it usesdelete[]
to free it, and to provideoperator[]
etc. If you use it with a non-array type, it usesdelete
. This needs partial template specialization likeAnother 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 bitsYet another use is with
std::iterator_traits<T>
. Iterators are required to define the nested typedefsvalue_type
,reference
and others to the correct types (for a const iterator,reference
would usually beT const&
, for example) so algorithms may use them for their work. The primary template uses type-members of the iterator type in turnFor pointers, that of course doesn't work. There is a partial specialization for them