模板声明说明

发布于 2024-10-01 02:58:24 字数 341 浏览 2 评论 0原文

我正在查看 C++ STL 向量模板代码以准确了解它是如何实现的。 我对模板编程有非常基本的了解,您能否对 STL 矢量的表达式摘录给出一个清晰的解释

typename _Alloc = std::allocator<_Tp> 

,如下:

template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
class vector : protected _Vector_base<_Tp, _Alloc>

谢谢您的所有帮助

I was looking at C++ STL vector template code to understand exactly how it is implemented.
I have very basic understanding of template programming, could you give a clear explanation of the expression

typename _Alloc = std::allocator<_Tp> 

excerpt from STL vector as below:

template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
class vector : protected _Vector_base<_Tp, _Alloc>

Thank you for all help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三五鸿雁 2024-10-08 02:58:24

这会为模板参数分配一个默认类型,这样您就不必在创建向量时添加它:

std::vector<int> v;

默认情况下,模板的第二个参数由类型 std::allocator<_Tp> 填充。

默认模板参数允许通过包含一些默认功能来缩短数据声明(您可以通过简单地为模板声明提供第二个参数来覆盖该功能)。

This assigns a default type to a template parameter, so that you don't have to add it whenever you create a vector:

std::vector<int> v;

By default, the second parameter of the template is filled by the type std::allocator<_Tp>.

Default template parameters allow to shorten data declarations by including some default functionality (that you can override by simply giving a second parameter to the declaration of the template).

老街孤人 2024-10-08 02:58:24

类模板参数可以具有默认参数,就像函数允许您为函数参数提供默认参数一样。

这允许您仅将 std::vector 与单个模板参数(值类型)一起使用,而无需显式指定分配器,因为大多数时候您都需要默认分配器。

std::vector<int>

std::vector<int, std::allocator<int> >

Class template parameters can have default arguments just as functions allow you to have default arguments for function parameters.

This allows you to use std::vector with only a single template argument, the value type, without having to specify the allocator explicitly, since most of the time you want the default allocator anyway.

This

std::vector<int>

is exactly the same as

std::vector<int, std::allocator<int> >
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文