9

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

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

现在我想从 a 中声明为 ' 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;
            }

        }

    }
}
4

2 回答 2

24

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

于 2010-12-27T15:12:26.663 回答
9

也许对您来说更好的方法是使用访问者-因此您只需编写一次 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);
于 2010-12-27T21:45:55.087 回答