获取Boost::图的顶点属性

c++ Getting vertex properties of a Boost::Graph

本文关键字:顶点 属性 Boost 获取      更新时间:2023-10-16

给定顶点:

class VertexProps {
  public:
    int id;
    float frame;
    string name;
};

我已经使用捆绑属性初始化了我的boost图。我知道我可以使用:

来获取框架
std::cout << "Vertex frame: " << boost::get(&VertexProps::frame, graph, vertex) << std::endl;
//Need to make this work: float frame = boost::get(&VertexProps::frame, graph, vertex);
//graph is a boost::adjacency_list and vertex is a boost::vertex_descriptor

然而,我想写一个更通用的函数或包装器,这样:

std::vector<float> frames;
std::string prop_name = "frame";
float frame = graph.get_vertex_prop(vertex, prop_name);
frames.push_back(frame);

我希望是这样的:

typedef boost::variant< int, unsigned int, float, std::string > PropValType;
typedef boost::vertex_bundle_type<Graph>::type PropIdType;
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
PropValType get_vertex_prop(Vertex& v, PropIdType pname)
{
  boost::get(pname, graph, v);
  //If pname = frame then return value as float (or cast boost::variant to float)
  //If pname = name then return value as a string
}

我想避免这样的事情:

PropValType get_vertex_prop(Vertex& v, std::string pname) {
 if (pname == "frame") {
   boost::get(&VertexProps::frame, graph, v)
   //return value as float
 }
 if (...)
}

在编译时没有任何宏魔术是无法做到这一点的。c++不允许字符串字面值作为非类型模板参数,并且具有非常弱的反射功能。

您提出的(并想要避免的)解决方案需要在运行时进行一些工作,通常应该避免。

宏观解决方案如下:

#define MY_GET(v, pname) boost::get(&VertexProps##pname, graph, v)
PropValType v = MY_GET(v, frame);