【问题标题】:boost::variant conversion to typeboost::variant 转换为类型
【发布时间】:2010-12-27 15:10:43
【问题描述】:

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

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

现在我想从 struct node 中声明为“value”的变量中获取一个值,所以我想我可以通用工作并调用函数:find_attribute&lt;long&gt;(attribute);,但是编译器说它不能从变体转换为长或我给它的任何其他类型。我做错了什么?

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

        }

    }
}

【问题讨论】:

    标签: c++ variant


    【解决方案1】:

    您必须使用 boost::get&lt;type&gt;(variant) 从变体中获取值。

    【讨论】:

      【解决方案2】:

      也许对您来说更好的方法是使用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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多