2014-04-07 123 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; 

分配器界面在設計之前模板的模板參數是語言的一部分,所以這是不是一種選擇。

如果今天要設計allocator API,有很多事情會做得不一樣,不幸的是我們仍然堅持我們所擁有的(以及由於試圖以半兼容的方式擴展而導致的持續複雜性)。

+0

哦哇,我怎麼不知道模板模板參數?就在你認爲你懂語言的時候,呃?很好的解決方案,以及一般的良好答案。謝謝! –

相關問題