面向Boost图形类型的前向结构声明

Forward declaration of struct for Boost graph typedef c++

本文关键字:结构 声明 Boost 图形 类型 面向      更新时间:2023-10-16

简短的问题描述:

基本上我想要

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

我该怎么做呢?

实际问题:

对于Boost连续最短路径算法,我需要将我的正向边映射到它们的反向边。我有以下代码:

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的完整类型,但那个当然没有初始化。我如何解决这个循环引用?

问题是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?