Valve without template

Each stl container takes an allocator as a parameter:

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

      

If you write your own class, you can 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);
  }

      

Because how could you know the size T?

+2


a source to share


3 answers


Ok if you wrote one that was not a template class, it only had to be for one type. Just replace T

with whatever type you want to use the distributor for.



Seems like a pointless exercise since you actually have templates available to you.

+2


a source


If you wanted to write an allocator for a single class, perhaps you ... although that will depend on the container you want to use it for.

The distributor must have this method:

template <class T>
class Allocator
{
public:
  template <class U>
  Allocator(const Allocator<U>& rhs);
};

      



Why? If you use say, a list, then you are not allocating space for the object T

, but instead the list will have some structure Node<T>

that contains one or two pointers to the previous / next nodes.

So when you go to Allocator<T>

, it will build from it Àllocator< Node<T> >

to perform its own distributions.

Now if you're thinking about STL containers this requirement is required list

, set

and map

. I'm not even sure if you leave without vector

and deque

, and in any case, you will not meet the requirements of the concept Allocator

.

+1


a source


std::allocator

itself is a template class, so if you want to replace it you need to use a template class.

Now, to say that it's pretty easy to write an allocator class that forwards allocation requests to another object:

class my_allocator
{
public:
    void *allocate(size_t size) { ... }
}

template <class T>
class my_std_allocator
{
public:
    pointer allocate(size_t count, const void *hint) { return static_cast<pointer>(m_my_allocator->allocate(count*sizeof(T))); }

private:
    my_allocator * const m_my_allocator;

}

      

0


a source







All Articles