Search code examples
c++templatesmetaprogrammingvariadic-templates

unpack variadic arguments and pass it's elements accordingly


suppose I got a struct i.e. Coord that contains two static member variables, then pass it as an argument of variadic template function variadic_print_coord(), how do I unpack the variadic expressions, to call the print_pair() function that shown below.

template<class T1, class T2>
void print_pair(T1 t1, T2 t2)
{
  std::cout << t1 << " and " << t2 << '\n';
}

template<class T1, class T2, class ...Ts>
void print_pair(T1 t1, T2 t2, Ts... ts)
{
  print_pair(t1, t2);
  print_pair(ts... );
}

template<int X, int Y>
struct Coord
{
  static const int valueX = X;
  static const int valueY = Y;
}

template<class... COORDs>
void variadic_print_coord()
{
  print_pair(COORD1::valueX, COORD1::valueY, COORD2::valueX, COORD2::valueY, ...,
             COORDs::valueX, COORDs::valueY);
  //how could I manipulating the pack expressions to get something like this 
}

int main()
{
  print_pair<Coord<0,1>, Coord<2,3>, Coord<4,5>>();
  //result:
  //0 and 1
  //2 and 3
  //4 and 5
}


many thanks!


Solution

  • You can use the following construct involving a fold expression

    template<class... COORDs>
    void variadic_print_coord()
    {
      (print_pair(COORDs::X, COORDs::Y), ...);
    }
    

    In this case you won't need the variadic version of print_pair, as the calls basically decouple.


    #include <iostream>
    
    template<class T1, class T2>
    void print_pair(T1 t1, T2 t2)
    {
      std::cout << t1 << " and " << t2 << '\n';
    }
    
    template<int X, int Y>
    struct Coord
    {
      static const int valueX = X;
      static const int valueY = Y;
    };
    
    template<class... COORDs>
    void variadic_print_coord()
    {
      (print_pair(COORDs::valueX, COORDs::valueY), ...);
    }
    
    int main()
    {
      variadic_print_coord<Coord<0,1>, Coord<2,3>, Coord<4,5>>();
      //result:
      //0 and 1
      //2 and 3
      //4 and 5
    }