2010-12-27 13 views
9

Mam następujący wariant z lib doładowania:boost :: variant konwersja do typu

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

teraz chcę, aby uzyskać wartość od zmiennej zadeklarowanej jako „value” w struct node, więc pomyślałem, może działać generycznie i wywoływać funkcję jako taką: find_attribute<long>(attribute);, jednak kompilator mówi, że nie może rzutować z wariantu na długi lub jakiegokolwiek innego typu, który mu podaję. Co ja robię źle?

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; 
      } 

     } 

    } 
} 

Odpowiedz

7

Być może lepszym sposobem dla ciebie jest użycie visitors - więc trzeba będzie napisać find_attribute tylko raz:

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); 
Powiązane problemy