boost :: variant转换为type [英] boost::variant conversion to type

查看:340
本文介绍了boost :: variant转换为type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从boost lib中有以下变体:

I have the following variant from the boost lib:

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

现在我想从一个声明为 / code>结构节点中的/ code>',所以我想我可以工作通用和调用函数如下: find_attribute< long>属性); ,但是编译器说它不能从变体到长或任何其他类型我给它。我做错了什么?

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

        }

    }
}


推荐答案

您必须使用 boost :: get< type>(variant) 获取变量的值。

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

这篇关于boost :: variant转换为type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆