如何将std::string打包成std::tuple<Ts...>?

3

我有一个参数包,如下所示:

<int, long, string, double>

并且像字符串这样

"100 1000 hello 1.0001"

如何解析这些数据并将它们打包成std::tuple<int, long, string, double>?


1
你首先需要将字符串分割成一个包含4个字符串的向量,每个值对应一个字符串。你可以使用std::string::findstd::string::substr等函数来实现。然后你可以按需转换每个值。对于字符串转整数,使用std::stoi。对于字符串转双精度浮点数,使用std::stod - Michael Sohnen
1个回答

11

一种方法是使用 std::apply 来展开 tuple 的元素,然后使用 istringstream 提取格式化数据并将其赋值给该元素。

#include <string>
#include <tuple>
#include <sstream>

int main() {
  std::string s = "100 1000 hello 1.0001";
  std::tuple<int, long, std::string, double> t;
  auto os = std::istringstream{s};
  std::apply([&os](auto&... x) {
    (os >> ... >> x);
  }, t);
}

Demo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接