Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading