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;
}
#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 :)
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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.