난 내가 컨테이너에 대한 사용자 지정 할당을 사용하는 경우 포함 된 유형 이름을 반복 할 필요가 있음을 좋아하지 않는다 :컨테이너 할당자가 할당하는 유형을 지정해야하는 이유는 무엇입니까?
template<typename T, size_t MyAllocatorArgument>
struct MyAllocator : public std::allocator<T>
{
// ... Usual allocator implementation
};
typedef std::vector<int, MyAllocator<int, 42>> int_container;
typedef std::vector<int, MyAllocator<long, 12>> int_container_wrong_allocator;
두 번째 라인 인 표준에 따라 정의되지 않은 동작, 대부분의 구현은 할당을 rebind
것이지만 올바른 유형으로
제 질문은 컨테이너와 할당자가 동일한 유형이어야한다는 요구 사항을 감안할 때,이 표준을 적용하거나 (또는 완전히 피할 수있는) 표준 기계가없는 이유와 사용자 오류 가능성을 제거하는 이유는 무엇입니까? ?
는 예를 들어, 표준 rebind
이 (효과적으로 할당 템플릿 매개 변수 중복을 만들기 위해) 익숙해 않는 것을 강제 할 수, 또는 아래에 사용될 수와 같은 패턴은 사용자가 한 번만 포함 된 유형 이름을 언급 있도록 :
template<size_t MyAllocatorArgument>
struct MyAllocator
{
// This would be something every allocator is required to expose.
template<typename T>
struct TypedAllocator : public std::allocator<T>
{
// This is where the normal implementation of the allocator would go.
// allocate, deallocate etc.
};
};
template<typename T, typename UntypedAllocator>
struct Container
{
// All containers would do this to get the actual allocator type they would use.
typedef typename UntypedAllocator::template TypedAllocator<T> TypedAllocator;
Container() : m_allocator(TypedAllocator()) {}
void useAllocator()
{
m_allocator.allocate();
// ... or whatever else containers need to do with allocators.
}
TypedAllocator m_allocator;
};
void allocator_test()
{
// Allocated type name isn't mentioned at point of use of container;
// only once for the container. The container does all the work.
Container<int, MyAllocator<42>> c1;
}
'rebind'를 사용하더라도 작성자는 템플릿 매개 변수를 사용하여 다른 클라이언트 유형에 대한 할당 자의 다양한 전문화를 제공 할 수 있습니다. –
@KerrekSB 질문 : "컨테이너와 할당자가 같은 유형이어야한다는 요구 사항을 감안할 때 왜이 표준을 시행하거나 (또는 완전히 피할 수있는) 표준 장비가없고 사용자 오류 가능성을 제거하는 이유는 무엇입니까? " 그래서 당신은 여전히 벡터를 생성 할 수있다 – 4pie0
할당자를 가진'allocator '은 B가 A에서 파생되면'B'를 할당하는 데 잠재적으로 사용될 수있다. 컨테이너와 할당 자 유형 간의 일치는 자연스럽지 만 어렵다. 그것은 필요한 경우 말할 수 있습니다. –
Sheljohn