Search code examples
c++templatesc++20stdstringstdtuple

how to pack a std::string as a std::tuple<Ts...>


I have a parameter pack like

<int, long, string, double>

and a string like

"100 1000 hello 1.0001"

how can I resolve these data and pack them into a std::tuple<int, long, string, double>


Solution

  • One way is to use std::apply to expand the elements of the tuple and use istringstream to extract the formatted data and assign it to the element

    #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