【发布时间】:2016-06-25 11:01:11
【问题描述】:
这个问题是Pointers to class members when iterating with boost::fusion 的后续问题,接受的解决方案在该处有效。
现在,我不仅想将(原始)值添加到属性映射中,还想使用漂亮的打印机来改进值的显示方式。这种机制也将用于值不易于打印的情况。
所以,有一些像这样的漂亮打印机:
template<typename T>
std::string prettyPrinter(const T& t);
template<>
std::string prettyPrinter(const std::string& s)
{
return "The string id: " + s;
}
template<>
std::string prettyPrinter(const int& i)
{
return "The int id: " + std::to_string(i);
}
我通过将 prettyPrinter 绑定到 boost::phoenix 演员扩展了上一个问题的解决方案:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/find.hpp>
#include <boost/phoenix/fusion/at.hpp>
#include <boost/phoenix.hpp>
#include <boost/mpl/range_c.hpp>
#include <iostream>
struct Vertex {
std::string id;
};
struct Edge {
int id;
};
BOOST_FUSION_ADAPT_STRUCT(Vertex, id)
BOOST_FUSION_ADAPT_STRUCT(Edge, id)
template <typename Tag, typename T_Graph>
void member_iterator(boost::dynamic_properties& dp, T_Graph& g)
{
using namespace boost;
using Bundle = typename property_map<T_Graph, Tag>::type;
using T_Seq = typename property_traits<Bundle>::value_type;
using Indices = mpl::range_c<unsigned, 0, fusion::result_of::size<T_Seq>::value>;
fusion::for_each(
Indices{},
[&, bundle=get(Tag{}, g)](auto i) {
auto name = fusion::extension::struct_member_name<T_Seq, i>::call();
using TempType = typename fusion::result_of::value_at<T_Seq, decltype(i)>::type;
//
// Interesting part starts here:
//
dp.property(
name,
make_transform_value_property_map(
phoenix::bind(
prettyPrinter<TempType>,
phoenix::at_c<i>(phoenix::arg_names::arg1)
),
bundle
)
);
}
);
}
using MyGraph = boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, Vertex, Edge>;
int main()
{
MyGraph g;
boost::dynamic_properties dp;
member_iterator<boost::vertex_bundle_t>(dp, g);
member_iterator<boost::edge_bundle_t>(dp, g);
}
我现在正在寻找一种更优雅的解决方案的可能性,因为@sehe 在评论中指出,使用phoenix::bind 可能不是这里的最佳选择。
【问题讨论】:
标签: c++ boost metaprogramming boost-fusion boost-phoenix