我见过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));
}
}
什么是构造for...
做?
最佳答案
截至 2021 年,这不是标准的 C++。
这是一种建议的语法(称为“扩展语句”),用于可以描述为 if constexpr
或多或少的循环模拟的内容。 : 一个编译时循环结构,在语法上展开。与普通循环相比,它的优势在于它允许迭代异构类型的结构。
此语法将允许编写如下循环:
std::tuple<int, const char *, double> t { 42, "hello", 69.420 };
for... (auto x : t) {
std::cout << x << std::endl;
}
意思大致相同: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;
}
在 for...
以上循环,在每次迭代中 x
变量具有不同的类型;可以说每次迭代都有一个独立的独立变量。在普通循环中,变量的类型在迭代之间共享,这意味着循环不能通过类型检查。这种语法最早是在 P1306R0 中提出的。 ,它还描述了一个相关但不同的
for constexpr
( the following revision 统一了两者)。 P1858R1为它引入了另一种语法,template for
,替换省略号语法。显然,这个特性将被包含在 C++23 中。
关于c++ - 关键字 'for' 后面带省略号的 for 语句有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66799707/