2011-08-01 53 views
3

給定一個頂點作爲獲取頂點屬性:C++一個boost ::圖

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

我已經初始化使用捆綁的性能提升我的圖表。我知道我可以用得到的框架:

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 (...) 
} 

回答

2

在編譯時沒有任何宏魔法。 C++不允許字符串文字作爲非類型的模板參數,並且具有非常細微的反射能力。

您提出的(並且想避免的)解決方案在運行時需要一些工作,通常應該避免。

宏的解決辦法是沿着這些線路:

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

好吧,我已經差不多相信這個事實我自己。但是有沒有辦法轉換成正確的類型?我試過float frame = * static_cast (boost :: get(&VertexProps :: pname,graph,v)) – Stephen

+0

我不明白你的意思。 'boost :: get(&VertexProps :: pname,graph,v)'已經返回一個'float'。那裏有什麼演員? – pmr

+0

你說得對。累了;編譯器告訴我「從'void *'無效轉換爲'float';我讀了錯誤的行號 – Stephen