C++:将模板声明为类成员
问题描述:
我想要一个node
类来构建树。 node
是一个模板类,模板论证_Data
和_Container
。对于模板论证中没有递归,我让_Container
成为一个类的模板类实例。我在node
中声明typedef _Data data_type
,并且想要使用node::container_type
,如node::data_type
。我能怎么做?C++:将模板声明为类成员
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
,所以你必须做一些事情,如: