2

是否可以在 Boost Graph Library 中使用标准库类型的捆绑属性,同时使用该类型的<<流运算符重载来满足write_graphviz

#include <boost/graph/graphviz.hpp>

namespace boost {
  namespace detail {
    namespace has_left_shift_impl {
      template <typename T>
      inline std::ostream &operator<<(std::ostream &o, const std::array<T,2> &a) {
        o << a[0] << ',' << a[1];
        return o;
      }
    }
  }
}

static_assert(boost::has_left_shift<
                std::basic_ostream<char>,
                std::array<double,2>
              >::value,"");

int main()
{
  using namespace boost;
  typedef adjacency_list<vecS, vecS, directedS, no_property, std::array<double,2>> Graph;
  Graph g;
  add_edge(0, 1, {123,456}, g);
  write_graphviz(std::cout, g, default_writer(),
                   make_label_writer(boost::get(edge_bundle,g)));
  return 0;
}

面对 Boost 静态断言,我将代码修改为上面的代码;从这里采纳一个建议,其中<<实现是在命名空间中定义的boost::detail::has_left_shift_impl。唉,我现在面临另一个错误:

/usr/include/boost/lexical_cast.hpp:1624:50: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
                 bool const result = !(out_stream << input).fail();

有没有办法提供可供使用的<<重载write_graphviz?我正在使用 Ubuntu 14.10 和 GCC 4.9.1。

4

1 回答 1

3

你甚至做不到

std::cout << g[add_edge(0,1,{123,456},g)];

不提供例如

inline static std::ostream& operator<<(std::ostream& os, std::array<double, 2> const& doubles) {
    return os << "{" << doubles[0] << "," << doubles[1] << "}";
}

现在,lexical_cast在正确的时间看到这些重载是非常难以移植的(主要是因为 ADL 不会帮助您处理std::arrayand double)。

相反,您可以使用值转换属性映射(当然这是只读的):

std::string prettyprint(std::array<double, 2> const& arr) {
    std::ostringstream oss;
    oss << "{" << arr[0] << "," << arr[1] << "}";
    return oss.str();
}

接着make_transform_value_property_map(prettyprint, get(edge_bundle, g))

Live On Coliru

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>

using namespace boost;

std::string prettyprint(std::array<double, 2> const& arr) {
    std::ostringstream oss;
    oss << "{" << arr[0] << "," << arr[1] << "}";
    return oss.str();
}

int main()
{
    using namespace boost;
    typedef adjacency_list<vecS, vecS, directedS, no_property, std::array<double,2>> Graph;
    Graph g;
    add_edge(0, 1, {123,456}, g);
    write_graphviz(std::cout, g, default_writer(),
            make_label_writer(make_transform_value_property_map(&prettyprint, get(edge_bundle, g))));
}

印刷

digraph G {
0;
1;
0->1 [label="{123,456}"];
}
于 2015-04-30T01:12:34.117 回答