2010-12-27 6 views
9

Tôi có biến thể sau từ tăng lib:chuyển đổi boost :: biến thể gõ

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

Bây giờ tôi muốn để có được một giá trị từ một biến khai báo là 'value' trong một struct node, vì vậy tôi nghĩ tôi có thể làm việc chung và gọi hàm như vậy: find_attribute<long>(attribute);, tuy nhiên trình biên dịch cho biết nó không thể truyền từ biến thể sang dài hoặc bất kỳ loại nào khác mà tôi cung cấp cho nó. Tôi đang làm gì sai?

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

     } 

    } 
} 

Trả lời

7

Có lẽ một cách tốt hơn cho bạn là sử dụng visitors - vì vậy bạn sẽ phải viết find_attribute chỉ một lần:

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