开发者

boost::variant conversion to type

开发者 https://www.devze.com 2023-02-01 02:45 出处:网络
I have the following variant from the boost lib: typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> 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; //ev开发者_运维问答en explicit cast doesn't wrok??
                //return temp;
            }

        }

    }
}


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号