C++ Parameter Pack Printing Example
예제1: 재귀
Example1: Using recursive function call
#include <iostream>
template<typename Arg>
void print_all(const Arg& arg){
std::cout << arg << std::endl;
}
template<typename Arg, typename ...Args>
void print_all(const Arg& arg, const Args&... args){
std::cout << arg << ',';
print_all(args...);
}
int main(){
print_all(1);
print_all(1, 2, 3, 4, 5);
return 0;
}
결과는
Result
1
1,2,3,4,5
예제2: 재귀 없이
Example2: Without recursion
C++11, C++14
#include <iostream>
template <typename Arg, typename... Args>
void print_all(const Arg& arg, const Args&... args) {
std::cout << arg;
int dummy[sizeof...(Args)] = { (std::cout << ',' << args, 0)... };
std::cout << std::endl;
}
int main(){
print_all(1);
print_all(1, 2, 3, 4, 5);
return 0;
}
콤마 연산자(comma operator)를 이용한 트릭
A Trick using a comma operator
C++17
#include <iostream>
template <typename Arg, typename... Args>
void print_all(const Arg& arg, const Args&... args) {
std::cout << arg;
((std::cout << ',' << args), ...);
std::cout << std::endl;
}
int main(){
print_all(1);
print_all(1, 2, 3, 4, 5);
return 0;
}
정식 기능인 fold expressions을 이용
Using Language feature: fold expressions
두 경우 모두 결과는
Result in both cases
1
1,2,3,4,5
두 예제 모두 콤마를 사이에만 넣기 위해서 함수의 첫 인자를 명시했습니다.