加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C,前向声明和递归数据类型

发布时间:2020-12-16 07:04:55 所属栏目:百科 来源:网络整理
导读:我希望能够有一个地图,其中值是指向地图的指针.就像是 std::mapKeyType,const_pointer_to_this_map's_value_type 我知道我可以使用const void *而不是const_pointer_to_this_map’s_value_type. 我已经看过循环数据类型定义的技巧,例如https://gist.github.c
我希望能够有一个地图,其中值是指向地图的指针.就像是

std::map<KeyType,const_pointer_to_this_map's_value_type>

我知道我可以使用const void *而不是const_pointer_to_this_map’s_value_type.

我已经看过循环数据类型定义的技巧,例如https://gist.github.com/tivtag/1208331或http://qscribble.blogspot.fr/2008/06/circular-template-references-in-c.html,但我不确定它们是否以及如何应用于我的案例.

在那里他们使用自己的类(Vertex和Edge; A和B),但是这里std :: map和std :: map :: value_type已经在STL头中定义了,我不能用Combo类实例化它们.

有没有办法定义上面的地图?

解决方法

只需将其包裹在一个结构中.您需要为类型指定名称才能引用它.

template<class T>
class Graph {
    std::map<T,const Graph<T>*> data;
public:
    // ...
};

在C 11中,您还可以使用带有前向声明的typedef的模板别名来执行此操作:

namespace {

template<class T>
struct GraphWrap {
    class type;
    typedef std::map<T,const typename GraphWrap<T>::type*> type;
};

}

template<class T>
using Graph = typename GraphWrap<T>::type;

当然,在这里使用std :: map可能有点误导,因为你使用key类型参数作为容器的值类型.就像Mooing Duck所说的那样,你似乎在建模一个有向图,每个节点最多有一个出边.如果你想用图表做一些事情,那里有图表库 – 如果你正在做其他事情,或者如果你只是想学习,那么这是另一个故事.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读