0

I need to output(cout) all the args for variable length template arguments. Thanks in advance.

 template <class... Args>
    void print(Args &&... args)
    {
        cout << sizeof...(args) << endl;
        //how to traverse ...args
        //expect output :1,2,3,4,5,6,7,8

    }

    int main()
    {
        print(1, 2, 4, 5, 6, 7, 8);
        return 0;
    }
Li Kui
  • 640
  • 9
  • 21
  • Possible duplicate of [Variadic template pack expansion](https://stackoverflow.com/questions/25680461/variadic-template-pack-expansion) – Artemy Vysotsky Sep 26 '17 at 04:55
  • 1
    They can't be traversed. You can *unpack* them into other expressions – M.M Sep 26 '17 at 04:55
  • You can unpack args using following syntax `int dummy[] = { 0, ( (void) (std::cout << std::forward(args) << ' '), 0) ... };` (C++11) – Artemy Vysotsky Sep 26 '17 at 05:05

2 Answers2

2
#include <iostream>

template <class T>
void print (T&& t) {
    std::cout << t << '\n';
}

template <class T, class... Args>
void print(T&& t, Args &&... args) {
  std::cout << t << ',';
  print(args...);
}

int main() {
  print(1, 2, 4, 5, 6, 7, 8);
  return 0;
}

Note that this calls cout once+ per element printed , when ideally, you'd construct a string and call cout once.

But that's on you :)

druckermanly
  • 2,694
  • 15
  • 27
1

Here is the sample code using C++17

#include <iostream>

template <class T, class... Args>
void print(T&& t, Args &&... args)
{
    std::cout << t;
    ((std::cout << ", " << std::forward<Args>(args)), ...) ;
    std::cout << '\n';
}

int main()
{
    print(1, 2, 4, 5, 6, 7, 8);
    print(9);
    return 0;
}

Not that I feel it is somehow superior to the accepted answer. Just to be complete...

Artemy Vysotsky
  • 2,694
  • 11
  • 20