举个例子,一个单向链表的节点可能定义如下
namespace example_part1
{
class node
{
node * next;
int value;
}
}
假设我们只有一个整数列表。此类允许有一个指向其自身类型的成员,因为无论底层数据结构的大小如何,指针都具有相同的大小。
现在,为什么不允许我这样做
namespace example_part2
{
using node = std::pair<example_part2::node *, int>;
}
?
我知道这似乎是一个愚蠢的例子,但我想知道更多这无法编译背后的原因。我实际上有类似的情况,它可能有用(不是 std::pair)。此外,假设这两个代码段来自不同的程序,即我没有节点自定义类以及在同一程序中作为节点别名的一对。
最佳答案
引用type alias declarations at cppreference的规范时, type-id 不得直接或间接引用引入的名称:
using identifier attr(optional) = type-id ; identifier - the name that is introduced by this declaration, which becomes either a type name template-parameter-list - template parameter list, as in template declaration type-id - abstract declarator or any other valid type-id (which may introduce a new type, as noted in type-id). The type-id cannot directly or indirectly refer to identifier. Note that the point of declaration of the identifier is at the semicolon following type-id.
关于命名空间,请注意 node
在std::pair<node *, int>
不涉及 node
命名空间 example_part1
因此仍然是一个未定义的类型名称。
关于c++ - 类型别名和自引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43689253/