boost :: variant转换为type

Ton*_*ion 9 c++ variant

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

typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
Run Code Online (Sandbox Code Playgroud)

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

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 23

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


小智 8

也许更好的方法是使用访问者 - 所以你必须只写一次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);
Run Code Online (Sandbox Code Playgroud)