为什么当我们有模板模板参数时allocator :: rebind是必需的?

编程入门 行业动态 更新时间:2024-10-12 18:16:43
本文介绍了为什么当我们有模板模板参数时allocator :: rebind是必需的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

每个分配器类都必须具有类似于以下界面的界面:

Every allocator class must have an interface similar to the following:

template<class T> class allocator { ... template<class Other> struct rebind { typedef allocator<Other> other; }; };

>

And classes that use allocators do something redundant like this:

template<class T, class Alloc = std::allocator<T> > class vector { ... };

但是为什么这是必要的?

But why is this necessary?

换句话说,他们不能只是说:

In other words, couldn't they have just said:

template<class T> class allocator { ... }; template<class T, template<class> class Alloc = std::allocator> class vector { ... };

这是更优雅,更少冗余,并且(在某些类似情况下)可能更安全吗? > 为什么他们去了 rebind 路由,这也导致更多的冗余(即你必须说 T 两次)?

which is both more elegant, less redundant, and (in some similar situations) potentially safer? Why did they go the rebind route, which also causes more redundancy (i.e. you have to say T twice)?

(类似的问题转到 char_traits 有 rebind ,他们仍然可以从模板模板参数中受益。)

(Similar question goes to char_traits and the rest... although they don't all have rebind, they could still benefit from template template parameters.)

但是如果你需要多于一个模板参数,这将不起作用。

其实很好用。

template<unsigned int PoolSize> struct pool { template<class T> struct allocator { T pool[PoolSize]; ... }; };

现在如果向量 :

template<class T, template<class> class Alloc> class vector { ... };

然后你可以说:

typedef vector<int, pool<1>::allocator> int_vector;

它可以很好地工作,不需要你 int 两次。

And it would work perfectly well, without needing you to (redundantly) say int twice.

而不是 Alloc :: template rebind< Other> 将会成为 Alloc< :: other

And a rebind operation inside vector would just become Alloc<Other> instead of Alloc::template rebind<Other>::other.

推荐答案

C ++ 11中的算法基础 ,第1卷,第4章, 35:

A quoted text from Foundations of Algorithms in C++11, Volume 1, chap 4, p. 35 :

template <typename T> struct allocator { template <typename U> using rebind = allocator<U>; };

示例用法:

allocator<int>::rebind<char> x;

编辑 :在C ++编程语言中,第4版,第34.4.1节, 998,在默认分配器类中注释'classical'rebind成员:

EDIT : In The C++ Programming Language, 4th edition, section 34.4.1, p. 998, commenting the 'classical' rebind member in default allocator class :

template<typename U> struct rebind { using other = allocator<U>;};

Bjarne Stroustupr写道:好奇的重新绑定模板是一个古老的别名,应该是: / p>

Bjarne Stroustupr writes this : "The curious rebind template is an archaic alias. It should have been:

template<typename U> using other = allocator<U>;

但是,分配器是在C ++支持这样的别名之前定义的。

However, allocator was defined before such aliases were supported by C++."

更多推荐

为什么当我们有模板模板参数时allocator :: rebind是必需的?

本文发布于:2023-10-31 13:37:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546242.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   当我们   参数   rebind   allocator

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!