简体   繁体   中英

What does a for statement with an ellipsis after the keyword 'for' do?

I have seen this code :

template <class... TYPES>
constexpr void tuple<TYPES...>::swap(tuple& other)
    noexcept((is_nothrow_swappable_v<TYPES> and ...))
{
    for...(constexpr size_t N : view::iota(size_t(0), sizeof...(TYPES))) {
        swap(get<N>(*this), get<N>(other));
    }
}

What does the construct for... do?

This is not standard C++ as of 2021.

This is a proposed syntax (named an 'expansion statement') meant for what can be described as a more-or-less loop analogue of if constexpr : a compile-time loop construct, unrolled syntactically. Its advantage over ordinary loops is that it allows iterating over heterogeneously-typed structures.

This syntax would allow writing loops like the following:

std::tuple<int, const char *, double> t { 42, "hello", 69.420 };

for... (auto x : t) {
    std::cout << x << std::endl;
}

meaning roughly the same as:

std::tuple<int, const char *, double> t { 42, "hello", 69.420 };

{
    auto x = std::get<0>(t);
    std::cout << x << std::endl;
}
{
    auto x = std::get<1>(t);
    std::cout << x << std::endl;
}
{
    auto x = std::get<2>(t);
    std::cout << x << std::endl;
}

In the for... loop above, in each iteration the x variable has a different type; it can be said that there is a separate, independent variable for each iteration. In an ordinary loop, the type of the variable is shared between iterations, which means the loop cannot pass type checking.

This syntax was first proposed in P1306R0 , which also describes a related, but distinct for constexpr ( the following revision unifies the two). P1858R1 introduced another syntax for it, template for , replacing the ellipsis syntax.

It is apparently expected that this feature will be included in C++23.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM