[英]How to forward declare a template class and use it as a member data in C++?
[英]c++: declare template as a class member
我想要一個node
類來構建一棵樹。 node
是具有模板爭論_Data
和_Container
的模板類。 為了避免模板爭執的遞歸,我讓_Container
作為代表類的模板類。 我在node
聲明typedef _Data data_type
,並想使用node::container_type
如node::data_type
。 我能怎么做?
template<
typename
_Data,
template<typename T> class
_Container = std::vector>
struct node
{
typedef _Data data_type;
//TODO container_type
typedef node<_Data, _Container> type;
typedef std::shared_ptr<type> ptr;
typedef _Container<ptr> ptrs;
Data data;
ptrs children;
};
在C ++ 11中,您可以使用類似以下的內容:
template<typename T, template<typename> class Container>
struct node
{
using data_type = T;
template <typename U>
using container_templ = Container<U>;
};
請注意, container_templ
不是類型(而container_templ<T>
是)。
還要注意, std::vector
與模板Container
不匹配,因為std::vector
需要一個額外的(默認)參數Allocator
,因此您必須執行以下操作:
template <typename T>
using My_Vector = std::vector<T>;
template<typename T, template<typename> class Container = My_Vector>
struct node;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.