boost::variant conversion to type

Tony The Lion picture Tony The Lion · Dec 27, 2010 · Viewed 12.3k times · Source

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

        }

    }
}

Answer

James picture James · Dec 27, 2010

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