I don’t like that I need to repeat the contained type name if I use a special dispenser for the container:
template<typename T, size_t MyAllocatorArgument>
struct MyAllocator : public std::allocator<T>
{
};
typedef std::vector<int, MyAllocator<int, 42>> int_container;
typedef std::vector<int, MyAllocator<long, 12>> int_container_wrong_allocator;
The second line is the undefined behavior in accordance with the standard, although in most implementations the rebinddistributor must be correct.
My question is that a container and a dispenser require a requirement for the same type, why is there no standard mechanism for its enforcement (or its complete elimination) and elimination of a potential user error?
For example, the standard may specify what rebindwill be used (to effectively make the dispenser template parameter redundant), or you can use a template similar to the one below, so the user only mentions the same name only once:
template<size_t MyAllocatorArgument>
struct MyAllocator
{
template<typename T>
struct TypedAllocator : public std::allocator<T>
{
};
};
template<typename T, typename UntypedAllocator>
struct Container
{
typedef typename UntypedAllocator::template TypedAllocator<T> TypedAllocator;
Container() : m_allocator(TypedAllocator()) {}
void useAllocator()
{
m_allocator.allocate();
}
TypedAllocator m_allocator;
};
void allocator_test()
{
Container<int, MyAllocator<42>> c1;
}
source
share