What is struct NIL { typedef NIL Head; }?



我正在阅读有关模板元编程的信息。我不明白这些台词的含义;以下有关在链接列表上进行元编程的代码涉及。

struct NIL {
typedef NIL Head;
typedef NIL Tail;
};
template <typename H, typename T=NIL> struct Lst {
    typedef H Head;
    typedef T Tail;
};
template <int N> struct Int{ static const int result = N; };
typedef Lst< Int<1>, Lst< Int<2>, Lst< Int<3> > > > OneTwoThree;

以上来自https://monoinfinito.wordpress.com/series/introduction-to-c-template-metaprogramming/。我将非常感谢任何指导的指导,即使结构nil的含义,该结构是nil nil nil and tym and typedef nil尾巴的指导。当然,零是一种类型,但是,如果我的头部nil nil nil头部,这是否意味着我在每个头部都有另一个递归头和尾巴?

no, typedef NIL Head;并不意味着您在每个NIL中都有 a NIL

这仅表示NIL::HeadNIL的另一个名称。同上NIL::Tail

这确实意味着您可以递归编写类型,例如NIL::Head::Tail::Tail::Tail::Head::Head也是NIL的名称。但是这里没有实际的递归类型。

NIL只是另一个名称。

它不是NULL,因为这是被采用的。

在这里,我们正在创建一个LISP,例如"头"one_answers"尾巴"的链接列表。要表示列表的结尾,请放置一个NIL

NIL满足列表的布局,但头部和尾巴都为 NIL。我自己很想写信:

struct NIL;
template <typename H, typename T=NIL> struct Lst {
  typedef H Head;
  typedef T Tail;
};

struct nil:lst {};

NIL作为空列表的名称更加清晰。

使NIL具有头部&amp;尾巴,某些模板元编程变得更容易(有些变得更难)。它们是相同类型的事实确实意味着从某种意义上说,NIL列表具有无限的长度。但从另一个意义上讲,它的长度为零,因为我们将长度定义为距离,直到我们达到NIL

typedef s不在"内部"类型中,而是在内部定义了数据成员的方式。他们更像指针,而不是成员。在非模板元图中:

struct node {
  node* head, *tail;
};
struct NIL:node{
  NIL() : node{this, this} {}
};

最新更新