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

345 Views Asked by At

I'm struggling transforming the usage of a boost::graph algorithm to a new set of implementation classes. I'm wondering: Is it even possible to access properties of an object, if the boost::graph only stores std::shared_ptr references? Like in the following:

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!

Is it possible to access members of a std::shared_ptr to use in the graph label writer write_graphviz or any other properties in the implementation?

Thank you!

1

There are 1 best solutions below

2
sehe On

Yeah just use a transforming property map

Live On 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));
}

Result:

digraph G {
0[label=a];
}