首页 > 解决方案 > 在模板中使用与模板类相同类型的类型别名它自己

问题描述

我不明白singly_linked.hpp中的一些代码:

template <class T>
struct singly_linked {
  // -- member types -----------------------------------------------------------

  /// The type for dummy nodes in singly linked lists.
  using node_type = singly_linked<T>;  // exactly type of node_type???

  /// Type of the pointer connecting two singly linked nodes.
  using node_pointer = node_type*;

  // -- constructors, destructors, and assignment operators --------------------

  singly_linked(node_pointer n = nullptr) : next(n) {
    // nop
  }

  // -- member variables -------------------------------------------------------

  /// Intrusive pointer to the next element.
  node_pointer next;
};

究竟是什么类型node_type?它会导致无限循环吗?例如,如果我有:

singly_linked<int> node;

那么是什么类型的singly_linked<int>::node_type呢?

标签: c++templates

解决方案


你误解了 的意思using node_type = singly_linked<T>;。它没有声明类型变量singly_linked<T>(这确实会导致无限递归并导致编译器错误)。相反,这为这种类型引入了一个别名:singly_linked<T>.

因此,询问类型是singly_linked<int>::node_type没有意义的,因为它本身就是一种类型。


推荐阅读