2010-12-27 7 views
9

Ich habe die folgende Variante aus dem Boost-lib:boost :: variant Konvertierung eingeben

typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant; 

Jetzt mag ich einen Wert aus einer Variable als ‚value‘ in einem struct node erklärt bekommen, so dass ich dachte, dass ich könnte generisch arbeiten und die Funktion als solche nennen: find_attribute<long>(attribute);, aber der Compiler sagt, es kann nicht von Variante zu lange oder irgendeinen anderen Typ ich gebe es. Was mache ich falsch?

template <typename T> 
T find_attribute(const std::string& attribute) 
{ 

    std::vector<boost::shared_ptr<node> >::iterator nodes_iter = _request->begin(); 

    for (; nodes_iter != _request->end(); nodes_iter++) 
    { 
     std::vector<node::attrib>::iterator att_iter = (*nodes_iter)->attributes.begin(); 
     for (; att_iter != att_iter; (*nodes_iter)->attributes.end()) 
     { 
      if (att_iter->key.compare(attribute) == 0) 
      { 
       return (T)att_iter->value; //even explicit cast doesn't wrok?? 
       //return temp; 
      } 

     } 

    } 
} 

Antwort

7

Vielleicht ein besserer Weg für Sie ist visitors verwenden - damit Sie find_attribute nur einmal schreiben müssen:

struct find_attr_visitor : public boost::static_visitor<> 
{ 
    template <typename T> void operator()(T & operand) const 
    { 
     find_attribute(operand); 
    } 
}; 
... 
// calling: 
boost::apply_visitor(find_attr_visitor(), your_variant);