Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::variant conversion to type

Tags:

c++

variant

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

        }

    }
}
like image 545
Tony The Lion Avatar asked Dec 27 '10 15:12

Tony The Lion


People also ask

What is boost :: variant?

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 .

How do I get the boost variant value?

You have to use boost::get<type>(variant) to get the value from a variant. Show activity on this post.


2 Answers

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

like image 79
James Avatar answered Oct 05 '22 22:10

James


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);
like image 39
crazylammer Avatar answered Oct 06 '22 00:10

crazylammer