简体   繁体   English

如何在C ++中声明自引用容器?

[英]How to declare a self-referential container in C++?

For a typedef of a struct in C, I can't do this: 对于C中的structtypedef ,我不能这样做:

typedef struct {
    unsigned id;
    node_t *left;
    node_t *right;
} node_t;

because node_t is not known until it is defined, so it can't be used in its own definition. 因为node_t在定义之前是未知的,所以它不能在它自己的定义中使用。 A bit of a Catch-22. 有点像Catch-22。 However, I can use this workaround to make the desired self-referential type: 但是,我可以使用此变通方法来创建所需的自引用类型:

typedef struct node_s node_t;
struct node_s {
    unsigned id;
    node_t *left;
    node_t *right;
};

Similarly, I would like to do something like this for a C++ container referring to itself: 同样,我想对引用自身的C ++容器做类似的事情:

typedef pair<unsigned, pair<node_t *, node_t * > > node_t;

but of course, the compiler complains that it's never heard of node_t before it's defined node_t , as it would for the struct typedef above. 但是当然,编译器抱怨node_t在定义node_t之前从未听说过node_t ,就像上面的struct typedef

So is there a workaround like for the struct ? 那么有没有像struct一样的解决方法? Or some better way to do this? 还是一些更好的方法来做到这一点? (And no, I don't want to use void pointers.) (不,我不想使用void指针。)

You can do it like this: 你可以这样做:

struct node_t : std::pair<unsigned, std::pair<node_t *, node_t * > >
{};

After struct node_t the compiler knows that the type with name node_t exists, similar to a forward declaration. struct node_t ,编译器知道名称为node_t的类型存在,类似于前向声明。

The language does not support forward declaration of typedef s. 该语言不支持typedef的前向声明。 Hence, you cannot use: 因此,你不能使用:

typedef pair<unsigned, pair<node_t *, node_t * > > node_t;

You can accomplish the notion of a container using struct node_t {...}; 您可以使用struct node_t {...};来完成容器的概念struct node_t {...}; , which I am sure needs no elaboration. ,我相信不需要详细说明。

You can self-reference a struct pointer if you name it (ie typedef struct <name> {...} ). 如果命名结构指针, 可以自引用结构指针(即typedef struct <name> {...} )。 I usually use the following idiom: 我通常使用以下习语:

typedef struct _node_t { // "Temporary" name "_node_t"
    unsigned id;
    struct _node_t *left; // Have to use "struct _node_t"
    struct _node_t *right;
} node_t; // "Final" name

That basically applies the previous answers to actual code. 这基本上适用于以前的实际代码答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM