简体   繁体   English

关键字“for”后带有省略号的 for 语句有什么作用?

[英]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?构造for...做什么?

This is not standard C++ as of 2021.截至 2021 年,这不是标准的 C++。

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.这是一个提议的语法(命名为“扩展语句”),用于可以描述为或多或少类似于if constexpr的循环:编译时循环构造,在语法上展开。 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;在上面的for...循环中,在每次迭代中, x变量都有不同的类型; 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).这种语法最初是在P1306R0中提出的,它还描述了一个相关但不同for constexpr以下修订将两者统一起来)。 P1858R1 introduced another syntax for it, template for , replacing the ellipsis syntax. P1858R1 为其引入了另一种语法template for ,取代了省略号语法。

It is apparently expected that this feature will be included in C++23.显然预计此功能将包含在 C++23 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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