Reputation: 500
I'm trying to do a simple PoC with variadic templates. Right now, my code is as follows:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
void println(const T& head) {
cout << head << endl;
}
template <typename T, typename ... Args>
void println(const T& head, Args&& ... args) {
cout << head << ", ";
println(args...);
}
int main() {
println(1,2,3,4,5,6);
}
Here, the separator is ,
, but I would like to be user provided, and also with a default value. However, trying something like void println(const T& head, const Args&... args, const string& sep = ",")
is not going to work due the parameter pack. Is there any workaround to do this in a simple manner?
Upvotes: 0
Views: 453
Reputation: 66230
I propose the following, non recursive, version. Based on a template defaulted value separator
#include <iostream>
template <char Sep = ',', typename T, typename ... Args>
void println (T const & head, Args const & ... args)
{ ((std::cout << head), ..., (std::cout << Sep << ' ' << args)) << std::endl; }
int main()
{
println(1,2,3,4,5,6);
println<':'>(1,2,3,4,5,6);
}
that prints
1, 2, 3, 4, 5, 6
1: 2: 3: 4: 5: 6
Upvotes: 5