没有模板的分配器 [英] allocator with no template

查看:61
本文介绍了没有模板的分配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个stl容器都将分配器作为参数:

Every stl container take an allocator as a parameter:

template < class T, class Allocator = allocator<T> > class vector;

如果编写自己的类,则可以使用自己的分配器. 但是可以在不使用模板的情况下编写自己的分配器吗?

If you write your own class It is possible to use your own allocator. But is it possible to write your own allocator without using templates?

例如,如果您不允许使用模板,则编写此功能并不容易

For example, writing this function is not easy if you are not allowed to use templates

 pointer allocate(size_type n, const_pointer = 0) {
    void* p = std::malloc(n * sizeof(T));
    if (!p)
      throw std::bad_alloc();
    return static_cast<pointer>(p);
  }

因为您怎么知道T的大小?

Because how could you know the size of T?

推荐答案

好吧,如果您编写的不是模板类,则只能用于单个类型.只需将T替换为您想要为其分配器的任何类型.

Well, if you wrote one that wasn't a template class, it would have to be for a single type only. Just replace T with whichever type you want an allocator for.

似乎无意义的练习,因为实际上您确实可以使用模板.

Seems like a pointless exercise, since you do in fact have templates available to you to use.

这篇关于没有模板的分配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆