如何改变STL的默认模板参数

to_ker 2011-08-02 09:12:40
STL中的vector有一个默认的内存分配器, 我想把它改变一下,形成新的模板类型,哪位高手指教一下怎么做

原有的大概这样
templete<class Tx, class Ty = allocator<tx>>
class vector
{
........
}

我想用这种方式定义一种新的数据类型
typedfef vector<Tx, MyAllocator<Tx>> MyVector

试了很多种办法都编绎不过
不想用MyVector继承vector的方法
...全文
125 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
未注销 2011-08-03
  • 打赏
  • 举报
回复
看下源码。
Michael_Xie 2011-08-03
  • 打赏
  • 举报
回复
或者
typedef vector<int, MyAllocator<int> > MyVector;
注意右边的两个>中间是有空格的。
Michael_Xie 2011-08-03
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 rendao0563 的回复:]

引用 9 楼 to_ker 的回复:

感谢楼上各位的回复, 我的MyAllocator是没有问题的,直接将allocate模板类拷贝出来, 修改了下类名名和alllocate与deallocate的函数内容,用vector<int, MyAllocator<int>>测试是正常的。

我想要的是定义一种新的MyVector,以后使用这个类型时就不用写vector<int, MyAllo……
[/Quote]

提供默认模板参数
template<typename T, typename allocator = MyAllocator<T> >
MyVector
{
...
};
rendao0563 2011-08-03
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 to_ker 的回复:]

感谢楼上各位的回复, 我的MyAllocator是没有问题的,直接将allocate模板类拷贝出来, 修改了下类名名和alllocate与deallocate的函数内容,用vector<int, MyAllocator<int>>测试是正常的。

我想要的是定义一种新的MyVector,以后使用这个类型时就不用写vector<int, MyAllocator<int>>
vector……
[/Quote]

默认参数
rendao0563 2011-08-02
  • 打赏
  • 举报
回复
那个要实现不少接口的. 要是不知道怎么弄. 可以参考一下loki 我csdn下载空间里面有.

http://rendao0563.download.csdn.net/
至善者善之敌 2011-08-02
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 dizuo 的回复:]
是不是MyAllocator的问题。
[/Quote]

放你的MyAllocator代码
downmooner 2011-08-02
  • 打赏
  • 举报
回复
stl容器都不建议继承 因为他的析构大多不是virtual

先模仿stl allocater写个自己的分配器。然后加入vector的参数即可
wjjjuniniho 2011-08-02
  • 打赏
  • 举报
回复
不用继承的话可以把vector设成自己设计的类的成员变量...
luciferisnotsatan 2011-08-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 michael_xie 的回复:]

那你提供一个新的内存分配器,譬如MyAllocator,你就可以这样用了:
vector<int, MyAllocator<int> > vec;
[/Quote]
++

失败报什么错?MyAllocator你怎么写的?
可以看下 stl源代码剖析
AlanBruce 2011-08-02
  • 打赏
  • 举报
回复
编译失败信息是什么?
ryfdizuo 2011-08-02
  • 打赏
  • 举报
回复
是不是MyAllocator的问题。
Michael_Xie 2011-08-02
  • 打赏
  • 举报
回复
那你提供一个新的内存分配器,譬如MyAllocator,你就可以这样用了:
vector<int, MyAllocator<int> > vec;
healer_kx 2011-08-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 michael_xie 的回复:]

那你提供一个新的内存分配器,譬如MyAllocator,你就可以这样用了:
vector<int, MyAllocator<int> > vec;
[/Quote]

UP


MyAllocator照着抄一份就行了。
to_ker 2011-08-02
  • 打赏
  • 举报
回复
感谢楼上各位的回复, 我的MyAllocator是没有问题的,直接将allocate模板类拷贝出来, 修改了下类名名和alllocate与deallocate的函数内容,用vector<int, MyAllocator<int>>测试是正常的。

我想要的是定义一种新的MyVector,以后使用这个类型时就不用写vector<int, MyAllocator<int>>
vector<string, MyAllocator<string>>这样的代码,直接写MyVector<int>, MyVector<string>,就和原有的vector的使用一样, 不过是内存分配器变了。

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧