[英]Nested class as a template parameter
我嘗試編寫一個自定義STL樣式的容器。 為簡單起見,我們說它是一個列表。 我查找了定義這樣一個容器的標准方法:
template <typename T, typename A = std::allocator<T> > class mylist;
現在,我想使用嵌套類來管理列表的節點:
(inside mylist)
class node {
T data;
node *next;
}
我的理解是,我不需要在node
定義之前放置template
說明符,因為編譯器將為mylist
的模板參數的每個組合實例化單獨的類mylist<T,A>::node
。
但是,現在我需要為T
本身的數據分配內存,而且還需要為它們的包裝器node
分配內存。 因此,我希望默認模板參數的類型為std::allocator<mylist<T>::node>
。 那時, mylist
還沒有被聲明,編譯器可以理解為難過:
error: `mylist' was not declared in this scope
如何解決這個難題? 有兩個限制:
node
,因為它需要訪問mylist
的分配器實例。 例如,我在node
上聲明了operator=
,其中大量內存管理以遞歸方式發生。 對於列表來說這可能是過度的,你可以從mylist
做到這一點,從而降低node
對A
的參數依賴性,但這對我正在實現的數據結構至關重要。 默認分配器的類型參數是什么,只是實際類型並不重要。 您可以使用std::allocator_traits
rebind_alloc
:
Alloc::rebind<T>::other
如果存在,否則Alloc<T, Args>
如果這個Alloc
是Alloc<U, Args>
得到你需要的東西:
template <typename T, typename A = std::allocator<T> >
class mylist {
class node { ... };
using NodeAlloc = typename std::allocator_traits<A>::template rebind_alloc<node>;
};
然后使用NodeAlloc
獲取node
。 這樣,如果用戶沒有指定分配器,您將獲得默認的std::allocator<T>
,然后使用std::allocator<node>
。 這正是您想要的,無需暴露node
。
我需要嵌套節點,因為它需要訪問
mylist
的分配器實例
不要那么肯定。 他們可以成為朋友:
template <typename, class> class list;
template <typename T>
struct node {
// ...
};
template <typename T, class Alloc=std::allocator<T> >
class list {
friend node<T>;
// ...
};
如果您不希望在文件外部訪問node
,只需在頭文件( .h
/ .hpp
)中省略它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.