How to define a recursive type?

前端 未结 5 886
孤独总比滥情好
孤独总比滥情好 2021-01-01 14:45

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,

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 15:30

    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::const_iterator _next;
    };
    

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

    struct Node;
    typedef std::list NodeList;
    
    struct Node {
        int _value;
        NodeList::const_iterator _next;
    };
    

    Edit: 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.

    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 
    struct Node_ {
        int _value;
        typename std::list::const_iterator _next;
    };
    
    typedef Node_<> Node;
    

提交回复
热议问题