반응형

Parameter Pack 각 요소 꺼내기

  • Pack Expansion -> array or tuple에 담기
#include <iostream>
#include <tuple>
using namespace std;

template<typename ... Types> 
void foo(Types ... args)
{
    // 각각의 타입별 값을 tuple 개별 요소로 추가
    tuple<Types...> tp(args...);

    cout << get<0>(tp) << endl;
    cout << get<1>(tp) << endl;
    cout << get<2>(tp) << endl;
}


int main()
{
    foo(1, 3.4, "AA");
}

 

  • 재귀 호출과 유사한 호출식을 사용하기
    • 1번째 인자는 이름 있는 변수 2번째 인자는 가변 인자로 구현
#include <iostream>
#include <tuple>
using namespace std;

void foo() {} // 재귀 호출 종료용

template<typename T, typename ... Types>
void foo(T value, Types ... args)
{
    cout << value << endl;
    foo(args...); 
    // 아래처럼 반복 호출 됨
    // foo(3.4, "AA");
    // foo("AA");
    // foo();
}


int main()
{
    foo(1, 3.4, "AA"); // value : 1, args : 3.4, "AA"
}

 

 

fold expression(C++17)

  • 이항 연산자를 사용해서 parameter pack안에 있는 요소에 연산을 수행하는 문법
  • parameter pack의 이름에서 ... 붙이지 않고 사용
    • pack expansion : args...
    • fold expression : args + ...
  • 4가지 형태(args:1,2,3,4)
    • unary right fold: ( args op ... )
      • (args + ... ) // 1+(2+(3+4))
    • unary left fold : (... op args)
      • (... + args) // ((1+2)+3)+4
    • binary right fold : ( args op ... op init)
      • ( args + ... + 10) // 1+(2+3(4+10)))
    • binary left fold : ( init op ... op args)
      • (10 + ... + args) // (((10+1)+2)+3)+4
#include <iostream>
using namespace std;

template<typename ... Types>
void foo(Types ... args)
{

    // args 값을 모두 호출할 수 있음
    //binary left fold : ( init op ... op args)
    (cout << ... << args);
}

int main()
{
    foo(1, 2, 3);
    (((cout << 1) << 2) << 3);
}
#include <iostream>
#include <vector>
using namespace std;

vector<int> v;

template<typename ... Types>
void foo(Types ... args)
{
    (v.push_back(args), ...);
    for (auto n : v)
        cout << n << endl;
}

int main()
{
    foo(1, 2, 3);
    (((cout << 1) << 2) << 3);
}
반응형

+ Recent posts