How can you have multiple lines or statements inside a C++ pack expansion?

976 views Asked by At

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;
        ((
            [&current_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.

1

There are 1 answers

8
Barry On BEST ANSWER

It reads much better if you declare the lambda separately and then fold over invoking it:

auto f = [&](auto& value){
    cout << i << ", " << value << "\n";
    ++i;
};
(f(current_value), ...);

You can also use something Boost.Mp11's tuple_for_each to avoid a layer of indirection:

size_t i = 0;
tuple_for_each(my_tuple, [&](auto& value){
    cout << i << ", " << value << "\n";
    ++i;
});

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:

size_t i = 0;
template for (auto& value : my_tuple) {
    cout << i << ", " << value << "\n";
    ++i;
}