[英]How to define a template class for a linked list node with pointer as template type
How to define a node template for a linked list? 如何为链表定义节点模板? I also want to keep the pointer type as template parameter so that I can change it to unique_ptr or shared_ptr depends on what available.
我还想将指针类型保留为模板参数,以便根据可用的内容将其更改为unique_ptr或shared_ptr。
template<typename T, typename NodePtr>
struct node{
T data;
NodePtr parent = nullptr;
};
The question is that how to initiate this class so that Nodeptr will be shared_ptr < Node <T ,what?> >
type? 问题是如何初始化此类,以便Nodeptr将成为
shared_ptr < Node <T ,what?> >
类型?
The "Simplest" solution I can think of is a variadic template template parameter: 我能想到的“最简单”解决方案是可变参数模板template参数:
template<class T,template<class ...> class PTR_T>
struct Node {
T data;
PTR_T<Node> parent{nullptr};
};
This works with both unique_ptr
and shared_ptr
like this: 可以与
unique_ptr
和shared_ptr
如下所示:
Node<int,std::shared_ptr> roots;
Node<int,std::unique_ptr> rootu;
As suggested by yourself, you'd have to introduce a type alias, if you want to use raw pointers: 正如您自己建议的那样,如果要使用原始指针,则必须引入类型别名:
template<class T> using raw_ptr = T*;
You only need to pass parameter T
: 您只需要传递参数
T
:
template <typename T>
struct node
{
T data;
node<T> * parent;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.