【问题标题】:Accessing member function of std::shared_ptr in boost::graph?在 boost::graph 中访问 std::shared_ptr 的成员函数?
【发布时间】:2016-02-17 10:26:24
【问题描述】:

我正在努力将 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 或实现中的任何其他属性中使用?

谢谢!

【问题讨论】:

    标签: c++ shared-ptr boost-graph boost-property-map


    【解决方案1】:

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

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

    结果:

    digraph G {
    0[label=a];
    }
    

    【讨论】:

    • 谢谢...虽然我目前的 boost 版本 (v1.50) 不知道 make_transform_value_property_map 我相信。之后,我必须检查我的编译器 (MSVC2010) 是否支持 Name{} 语法。
    • Transform-value 属性映射于 2012 年 3 月 25 日推出 r77535,这意味着它至少在 1.56 中。我有一个替代的想法。坚持
    猜你喜欢
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    相关资源
    最近更新 更多