如何在C ++中模拟递归类型定义? [英] How can I emulate a recursive type definition in C++?

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

问题描述

昨天我询问了以下问题,为方便起见,转载于此;

Yesterday I asked the following question, reproduced here for convenience;

对于我的一个项目,我真正想做的是这样(简化到最低限度);

"For one of my projects, what I really wanted to do was this (simplifying it to the bare minimum);

struct Move
{
    int src;
    int dst;
};

struct MoveTree
{
    Move move;
    std::vector<MoveTree> variation;
};

我必须承认,我认为不可能直接做到这一点,我认为一个MoveTree的向量在MoveTree将是verboten,但我尝试了它,它的作品很好,我使用的是Microsoft Visual Studio 2010 Express。

I must admit that I assumed that it wouldn't be possible to do this directly, I thought a vector of MoveTree s within a MoveTree would be verboten. But I tried it anyway, and it works beautifully. I am using Microsoft Visual Studio 2010 Express.

这是可移植的吗?我有什么需要担心的?

Is this portable ? Is it good practice ? Do I have anything to worry about ?"

基本上社区的答案是否定的,我不能这样做安德烈禁止它,所以事实上它的意思是我只是幸运。

Basically the answer from the community was no, I couldn't do this, the standard forbids it, so the fact that it works means I am just getting lucky.

所以我的新问题是。如何在法律C ++中实现我想要的简单功能,而不会增加一堆令人讨厌的复杂性和痛苦?

So my new question is. How can I implement the simple functionality I want in legal C++, without adding a whole heap of nasty complexity and pain ?

推荐答案

你需要使用指针和动态分配。你应该使用智能指针,以确保你不会泄漏任何东西。 boost :: shared_ptr 允许类型不完整,因此这是合法的:

You'll need to use pointers, and dynamic allocation. And you should use smart pointers, to ensure you don't leak anything. boost::shared_ptr allows the type to be incomplete, and therefore this is legal:

std::vector< boost::shared_ptr<MoveTree> > variation;

(我不知道0x std :: shared_ptr TBH,但它应该是一样的)。

(I don't know about 0x std::shared_ptr TBH, but it should be the same).

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

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