I have the following variant from the boost lib:
typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
Now I want to get a value from a variable declared as 'value
' in a struct node
, so I thought I could work generic and call the function as such: find_attribute<long>(attribute);
, however the compiler says it cannot cast from variant to long or any other type I give it. What am I doing wrong?
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;
}
}
}
}
boost::variant is defined in boost/variant. hpp . Because boost::variant is a template, at least one parameter must be specified. One or more template parameters specify the supported types. In Example 24.1, v can store values of type double , char , or std::string .
You have to use boost::get<type>(variant) to get the value from a variant. Show activity on this post.
You have to use boost::get<type>(variant)
to get the value from a variant.
Maybe a better way for you is to use visitors - so you will have to write find_attribute only once:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With