The Variadic Template Parameter Pack
Learn how to use variadic template parameter packs in C++, including constructing them and creating functions like make_string().
The variadic template parameter pack enables programmers to create template functions that can accept any number of arguments.
An example of a function with a variadic number of arguments
If we were to create a function that makes a string out of any number of arguments without variadic template parameter packs, we would need to use C-style variadic arguments (just like printf()
does) or create a separate function for every number of arguments:
Press + to interact
auto make_string(const auto& v0) {auto ss = std::ostringstream{};ss << v0;return ss.str();}auto make_string(const auto& v0, const auto& v1) {return make_string(v0) + " " + make_string(v1);}auto make_string(const auto& v0, const auto& v1, const auto& v2) {return make_string(v0, v1) + " " + make_string(v2);}// ... and so on for as many parameters we might need
This is the intended use of our function:
Press + to interact
auto str0 = make_string(42);auto str1 = make_string(42, "hi");auto str2 = make_string(42, "hi", true);std::cout<<str0<<"\n"<<str1<<"\n"<<str2<<"\n";
If we require a large number of arguments, this becomes tedious, but with a parameter pack, we can implement this as a function that accepts an ...