【问题标题】:Forward declaration of struct for Boost graph typedef c++Boost graph typedef c ++的结构前向声明
【发布时间】:2014-06-04 15:37:03
【问题描述】:

简短的问题描述:

基本上我想要

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

【问题讨论】:

  • @aschepler 这很可能是我的问题的解决方案......我现在正在尝试。
  • @aschepler 是的,就是这样!如果您将其作为答案发布,我会接受它作为解决方案 xD

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


【解决方案1】:

问题是无法定义struct Type(取决于大小和内存布局)until container&lt;Type&gt; 被实例化和定义,但这取决于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?了解更多关于前向声明的细节......

【讨论】:

  • 在我的情况下,有时会故意将对象保留为未定义。 shared_ptr 可以解决这个问题吗?因为MyType::value_type &amp; member 不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多