我不喜歡,我有如果我使用一個自定義的分配器容器重複包含類型名:爲什麼容器分配器需要指定他們分配的類型?
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
'分配器'可以潛在地用於分配'B's如果B派生自A.容器和分配器類型之間的對應似乎很自然,但它很難(對我來說)說是否有必要。 – Sheljohn