如何定义一个递归类型? [英] How to define a recursive type?

查看:102
本文介绍了如何定义一个递归类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个清单。列表中的一个条目将存储一个值以及到列表中另一个条目的迭代器。如何定义此类型?

I want to have a list. An entry in the list would store a value as well as an iterator to another entry in the list. How do I define this type? It'd be something like this, but syntactically correct.

typedef list<pair<int, MyList::const_iterator>> MyList;


推荐答案

让问题由内而外用户定义的类型来破坏声明的递归:

Let's turn the problem inside-out with a sprinkle of user-defined types to break the declarations' recursion :

struct Node {
    int _value;
    std::list<Node>::const_iterator _next;
};

如果要使用typedef,可以:

If you want to use a typedef, well you can :

struct Node;
typedef std::list<Node> NodeList;

struct Node {
    int _value;
    NodeList::const_iterator _next;
};

编辑:为T.C.提醒我,实例化具有不完整类型 的标准容器可能是未定义行为(某些标准库实现确实可以保证未实现)。 因此,让我们将所有内容推迟到以后。

As T.C. reminded me, instantiating standard containers with incomplete types may be Undefined Behaviour (some standard library implementations do guarantee it's not). So, let's postpone all of it to a later point.

编辑:嗯,这也无济于事。因此,请验证您的 std :: list 实现是否支持不完整的类型(或者相信它可以做到这一点,说实话,这通常是行得通的),或者使用Boost :: containers。 / p>

Edit: Well that doesn't help either. So, verify that your std::list implementation supports incomplete types (or trust it to do so, it often works to be honest), or use Boost::containers.

template <class = void>
struct Node_ {
    int _value;
    typename std::list<Node_>::const_iterator _next;
};

typedef Node_<> Node;

这篇关于如何定义一个递归类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆