Boost graph typedef c ++的struct的前向声明

时间:2014-06-04 15:37:04

标签: c++ boost forward-declaration circular-reference

简短问题说明:

基本上我想要

struct Type;
typedef container<Type> MyType;
struct Type{
    MyType::sometype member;
}

现在,我该怎么做?

实际问题:

对于Boost Succesive Shortest Path算法,我需要将前沿映射到它们的反向。我有以下代码:

struct VertexProperty { };
struct EdgeProperty;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, VertexProperty, EdgeProperty> DirectedGraph;

struct EdgeProperty {
    double edge_capacity; //capacity: 1 for forward, 0 for reverse
    double edge_weight; //cost
    DirectedGraph::edge_descriptor reverse_edge; //reverse edge mapping

    //forward edge constructor:
    EdgeProperty(double distance, DirectedGraph::edge_descriptor reverseEdge) :
            edge_capacity(1), edge_weight(distance), reverse_edge(reverseEdge) {
    };

    //reverse edge constructor
    EdgeProperty(double distance) :
            edge_capacity(0), edge_weight(-distance) {
    };

};

但是,现在我收到以下错误:

/usr/include/boost/pending/property.hpp:35:7: error: ‘boost::property<Tag, T, Base>::m_value’ has incomplete type
../src/Tester.cpp:21:8: error: forward declaration of ‘struct EdgeProperty’

我想这是有道理的:对于DirectedGraph :: edge_descriptor我需要完整类型的EdgeProperty,但那个当然没有初始化。如何解决此循环引用?

1 个答案:

答案 0 :(得分:1)

问题是struct Type无法定义(最大尺寸和内存布局)until container<Type>被实例化和定义,但这取决于struct Type的定义....导致循环依赖。

使用指针或智能指针中断依赖关系,在指定其指向类型之前可以确定其大小和布局。

例如:

#include <vector>
#include <memory>

struct Type;
typedef std::vector<Type> MyType;
struct Type{
    std::shared_ptr<MyType::value_type> member;
};

int main() {
        Type t;
}

您可以参考When can I use a forward declaration?了解有关前向声明的详细信息......