Suppose that I have some simple code like the one below, which just prints all of the values in a tuple and keeps track of the current iteration.
#include <iostream>
#include <tuple>
#include <utility>
using std::cout;
int main() {
std::tuple<int, double, size_t, unsigned, short, long long, long> my_tuple(7, 4, 1, 8, 5, 2, 9);
//Can you spot the pattern? :)
std::apply(
[](auto&&... current_value) {
size_t i = 0; //This is only executed once
((
cout << i++ << ", " << current_value << "\n" //This is repeated the length of the tuple
), ...);
}, my_tuple
);
return 0;
}
If I wanted to, for example, only print the tuple value if the index was greater than 2, how could I do this? I can't simply put an if
before the cout
because statements are not allowed (got [cquery] expected expression
on repl.it).
More generally, how can I do things like multiple lines of code or statements within a pack expansion?
Using a lambda inside works, e.g.
std::apply(
[](auto&&... current_value) {
size_t i = 0;
((
[¤t_value, &i](){
cout << i << ", " << current_value << "\n";
++i;
}()
), ...);
}, my_tuple
);
But I can't imagine that this is is the most efficient (or intended) solution.