0

I came across this syntax while reading up on std::integer_sequence.

What does this double bracket do? It looks like some form of loop. Does it only work with non-type template parameters? Must it be in the same order as the parameters? Can we iterate backwards? Skip a number?

// pretty-print a tuple
template<class Ch, class Tr, class Tuple, std::size_t... Is>
void print_tuple_impl(std::basic_ostream<Ch,Tr>& os,
                      const Tuple& t,
                      std::index_sequence<Is...>)
{
    ((os << (Is == 0? "" : ", ") << std::get<Is>(t)), ...);
}
Type Definition
  • 75
  • 1
  • 13
  • 5
    Fold expressions – Quimby Jun 09 '22 at 18:11
  • maybe related, another trial with this mechanism on my anwser [initialize tuple with a fixed-length array element](https://stackoverflow.com/a/71316271/3972710) – NGI Jun 09 '22 at 18:28
  • Also note that the `std::index_sequence` here isn't necessary to output a tuple to a `basic_ostream`. The page for [`std::apply`](https://en.cppreference.com/w/cpp/utility/apply) has a way to do it where you still have a comma, but don't need an index sequence. – Kevin Anderson Jun 09 '22 at 20:05

1 Answers1

2

There is documentation about this: fold expression

In short, in this case ... means repeating the specified operator for all parameters in the pack. So, in this case, it will be unpacked as a sequence of expressions separated by commas for each subsequent element of Is, like this:

(os << "" << std::get<0>(t)), (os << ", " << std::get<1>(t)), (os << ", " << std::get<2>(t)), (os << ", " << std::get<3>(t))
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Cycxyz
  • 171
  • 2