boost::variant conversion to type
Asked Answered
N

2

9

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

        }

    }
}
Neediness answered 27/12, 2010 at 15:10 Comment(0)
O
24

You have to use boost::get<type>(variant) to get the value from a variant.

Orchardist answered 27/12, 2010 at 15:12 Comment(0)
J
9

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);
Jamison answered 27/12, 2010 at 21:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.