处理包含boost :: variant的地图 作为值数据类型

问题描述 投票:0回答:1

我有一个地图数据结构,包含一个字符串作为键,多个数据类型作为值。我在实例化时填充了地图。我面临的问题是,当我在地图上迭代并尝试访问每个键的值时,我遇到了一些错误。我相信返回值可能需要从variant转换为其实际数据类型。我真的不知道如何访问它。

这是地图的定义:map> mapToBeProcessed;

map<string,boost::variant<int,double, long long, string>> mapToBeProcessed;

for(auto &x: mapToBeProcessed)
{
  if(ini.hasField(x.first))
  {
    b << x.first << x.second;
  }
}

//

当我试图访问地图的值时,问题就出现了:x.second

c++
1个回答
1
投票

您可以访问变体,将函数应用于活动成员。

struct stream_visitor {
    using result_type = void;
    template <typename T>
    void operator()(T& t) { os << name << t; }
    std::ostream & os;
    std::string name;
}

map<string,boost::variant<int,double, long long, string>> mapToBeProcessed;

for(auto &x: mapToBeProcessed)
{
  if(ini.hasField(x.first))
  {
    boost::apply_visitor(stream_visitor{ b, x.first }, x.second);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.