访问boost::graph中std::shared_ptr的成员函数

Accessing member function of std::shared_ptr in boost::graph?

本文关键字:ptr 成员 函数 std boost graph 访问 shared      更新时间:2023-10-16

我正在努力将boost::graph算法的用法转换为一组新的实现类。我想知道:如果boost::graph只存储std::shared_ptr引用,是否可以访问对象的属性?类似于以下内容:

class Vert { 
public:
    Vert();
    Vert(std::string n);
    std::string getName() const;
    void setName( std::string const& n );
private:
    std::string name; 
};
typedef std::shared_ptr<Vert> Vert_ptr;
using namespace boost;
typedef boost::adjacency_list<vecS, vecS, directedS, Vert_ptr> Graph;
Graph g;
Vert_ptr a( new Vert("a"));
add_vertex( a, g );
std::ofstream dot("test.dot");
write_graphviz( dot, g, make_label_writer(boost::get(&Vert::getName,g))); //ERROR!

是否可以访问std::shared_ptr的成员以在图形标签编写器write_graphviz或实现中的任何其他属性中使用?

谢谢!

是的,只需使用转换属性映射

在Coliru上直播

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/property_map/transform_value_property_map.hpp>
#include <fstream>
#include <memory>
using namespace boost;
class Vert { 
public:
    Vert(std::string n="") : name(n) { }
    std::string getName() const { return name; }
    void setName( std::string const& n ) { name = n; }
private:
    std::string name; 
};
typedef std::shared_ptr<Vert> Vert_ptr;
struct Name { std::string operator()(Vert_ptr const& sp) const { return sp->getName(); } };
int main() {
    typedef boost::adjacency_list<vecS, vecS, directedS, Vert_ptr> Graph;
    Graph g;
    Vert_ptr a( new Vert("a"));
    add_vertex( a, g );
    std::ofstream dot("test.dot");
    auto name = boost::make_transform_value_property_map(Name{}, get(vertex_bundle,g));
    write_graphviz( dot, g, make_label_writer(name));
}

结果:

digraph G {
0[label=a];
}