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;
}
To access variadic arguments, we must include the <stdarg. h> header.
A variadic function allows you to accept any arbitrary number of arguments in a function.
Variadic functions are functions (e.g. printf) which take a variable number of arguments.
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.
Variadic function templates in C++. Variadic templates are template that take a variable number of arguments. Variadic function templates are functions which can take multiple number of arguments.
Douglas Gregor and Jaakko Järvi came up with this feature for C++. Variadic arguments are very similar to arrays in C++. We can easily iterate through the arguments, find the size (length) of the template, can access the values by an index, and can slice the templates too.
In your template, you can then call another method with that parameter pack, by expanding (or unpacking) it into the function argument list. For instance, with “values…”: template <class... T_values>
The C programming language provides a solution for this situation and you are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function.
First of all, you forgot the
#include <tuple>
And the syntax you're probably looking for is:
return std::make_tuple(get<Ts>(stream)...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With