boost :: variant转换为type

时间:2010-12-27 15:10:43

标签: c++ variant

我有来自boost lib的以下变体:

typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;

现在我想从value中声明为“struct node”的变量中获取一个值,所以我认为我可以使用泛型并按原样调用函数:find_attribute<long>(attribute);,但编译器说它不能从变量转换为long或我给它的任何其他类型。我做错了什么?

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

        }

    }
}

2 个答案:

答案 0 :(得分:23)

您必须使用boost::get<type>(variant)从变体中获取值。

答案 1 :(得分:8)

也许更好的方法是使用visitors - 所以你只需要写一次find_attribute:

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