【问题标题】:Retrieve values from data structure holding variant data types without specifying the return type从包含变体数据类型的数据结构中检索值而不指定返回类型
【发布时间】:2019-04-29 13:47:54
【问题描述】:

我目前正在使用以字符串数据类型作为键和变量值的映射。我依靠 boost::variant 库来定义地图数据类型。我目前正在关注一些关于 boost::variant 的教程,用于从地图中提取值,而无需在迭代时指定我想要检索的确切数据类型值。 来源:https://theboostcpplibraries.com/boost.variant 我想要通用数据类型的最后一个示例,但不是打印我要返回的值。 以下内容似乎无法正常工作。

struct output : public boost::static_visitor<>
{
  template <typename T>
  T operator()(T t) const { return t }
};

我还实例化了一个映射,同时使用字符串数据类型作为键和 boost::variant 类型作为值填充它;稍后遍历地图并处理值。

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

for(auto &x: _keyPairValue)
{
  // appending a key pair value to a bson object which is part of mongo sdk
  b << x.first << boost::apply_visitor(output{},x.second);
}

【问题讨论】:

  • 请展开 "...似乎无法正常工作..." 所以我们知道问题出在哪里。
  • 小记:从 C++17 开始,你应该也可以使用 std::variant 代替。
  • 你能提供一个minimal reproducible example吗?我觉得这个问题很难理解......

标签: c++ boost


【解决方案1】:

我想要通用数据类型的最后一个示例,但不是打印值,而是返回它们。

您可能想要operator() 重载,例如:

struct process : public boost::static_visitor<>
{
  void operator()(double d)
  {
      // process d ...
  }
  void operator()(char c)
  {
       // process c ...
  }
  void operator()(const string& s)
  {
      // process s ...
  }
};

int main()
{
  boost::variant<double, char, std::string> v;
  v = 3.14;
  boost::apply_visitor(process{}, v);
  v = 'A';
  boost::apply_visitor(process{}, v);
  v = "Boost";
  boost::apply_visitor(process{}, v);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多