0

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?

Norhther
  • 545
  • 3
  • 15
  • 35
  • Pass the separator in the first parameter? – HolyBlackCat Apr 16 '21 at 16:27
  • @HolyBlackCat a default parameter should be at the end of the list of parameters. – Norhther Apr 16 '21 at 16:30
  • I'd do two different functions then, one that always uses comma, and the other one with a custom separator. Or you want this just to practice variadic templates? – HolyBlackCat Apr 16 '21 at 16:33
  • 1
    If the separator is a single char... pass it as template non type parameter? Something as `template `? That you can call `println<':'>(1,2,3,4,5,6);` – max66 Apr 16 '21 at 16:34
  • @max66 I thought this, but the syntaxis is really ugly... I would like to pass it as a parameter. – Norhther Apr 16 '21 at 16:37
  • Similar question: https://stackoverflow.com/questions/62216484/combining-function-parameter-pack-and-default-arguments – A.Hristov Apr 16 '21 at 17:41

1 Answers1

5

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
max66
  • 65,235
  • 10
  • 71
  • 111