c++ - 类型别名和自引用

标签 c++ self-reference type-alias

举个例子,一个单向链表的节点可能定义如下

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.

关于命名空间,请注意 nodestd::pair<node *, int>不涉及 node命名空间 example_part1因此仍然是一个未定义的类型名称。

关于c++ - 类型别名和自引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43689253/

相关文章:

c++ - 使用 boost::beast 处理大型 http 响应

c++ - TCP连接失败

c++ - std::function 的类型别名

javascript - JavaScript 对象中的自引用是否会导致性能不佳?

elm - 何时在Elm中使用类型别名与单值联合类型

constructor - 如何将构造函数添加到 Julia 中的类型别名?

c++ - 在网页上部署 Firebreath 插件,无需手动安装

java - 未定义的行为

ruby-on-rails - 我正在尝试将关系模型中的关注者状态从 'requested' 更改为 'approved'

theory - 生成 self 引用程序的工具?