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.
It reads much better if you declare the lambda separately and then fold over invoking it:
You can also use something Boost.Mp11's
tuple_for_each
to avoid a layer of indirection:which is a much more direct way of doing such a thing than going through
std::apply
. Even if you don't want to use Boost.Mp11 (and you should want to), this is fairly easy to implement.There was a language proposal for something called expansion statements which would make this a first-class language feature. It didn't quite make C++20, but could be in C++23: