Search code examples
c++c++17variadic-templatesvariadic-functions

C++: How call a function with type parameter on variadic template arguments?


So I have a function with variadic template arguments and I'm trying to invoke a method (with a type parameter) for every argument, pack every result value in a std::tuple and return it. However variadic templates are pretty hard for me and I haven't fully understood them yet.

Is it even possible to realize this in C++?

Here's my code so far (which has an error in the getMultiple function). Thank you very much for helping!

#include <iostream>
#include <fstream>
#include <sstream>

template<typename T>
T get(std::istream &stream) {
    T data;
    stream >> data;
    return data;
}

template<typename ... Ts>
std::tuple<Ts...> getMultiple(std::istream &stream) {
    // What am I doing wrong here?
    return std::make_tuple((get<Ts...>(stream)));
}

int main() {
    std::istringstream stream("count 2");
    auto [command, number] = getMultiple<std::string, int>(stream);

    return 0;
}

Solution

  • First of all, you forgot the

    #include <tuple>
    

    And the syntax you're probably looking for is:

    return std::make_tuple(get<Ts>(stream)...);