2014-04-07 2 views
4

난 내가 컨테이너에 대한 사용자 지정 할당을 사용하는 경우 포함 된 유형 이름을 반복 할 필요가 있음을 좋아하지 않는다 :컨테이너 할당자가 할당하는 유형을 지정해야하는 이유는 무엇입니까?

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; 
} 
+0

'rebind'를 사용하더라도 작성자는 템플릿 매개 변수를 사용하여 다른 클라이언트 유형에 대한 할당 자의 다양한 전문화를 제공 할 수 있습니다. –

+0

@KerrekSB 질문 : "컨테이너와 할당자가 같은 유형이어야한다는 요구 사항을 감안할 때 왜이 표준을 시행하거나 (또는 ​​완전히 피할 수있는) 표준 장비가없고 사용자 오류 가능성을 제거하는 이유는 무엇입니까? " 그래서 당신은 여전히 ​​벡터를 생성 할 수있다 – 4pie0

답변

2

좋은 질문입니다. 귀하의 제안은 표준 체계에 대한 하나의 가능한 대안입니다. 또 다른는 템플릿 템플릿 매개 변수를 사용했을 : 템플릿 템플릿 매개 변수는 언어의 일부가되기 전에 그 옵션이 없었다

template<typename T> 
class AnAllocator 
{ ... }; 

template<typename T, template <typename> class Alloc = std::allocator> 
class Vector 
{ 
    typedef Alloc<T> allocator_type; 
    ... 
}; 

Vector<int, AnAllocator> v; 

할당자는 인터페이스가 설계되었습니다.

할당 자 API가 오늘 설계 될 경우 다르게 수행 될 수있는 많은 작업이 있습니다. 불행히도 우리는 우리가 가지고있는 것과 만만합니다 (그리고 반쯤 호환되는 방식으로 확장하려고 시도하여 복잡성이 계속됨).).

+0

오, 어떻게 템플릿 템플릿 매개 변수에 대해 알지 못했습니까? 언어를 알고 있다고 생각할 때, 어? 좋은 해결책, 일반적으로 좋은 대답. 감사! –