0

Below is from an authoritative C++ proposal:

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

However, I cannot compile the following code in the same way:

#include <iostream>
#include <vector>

template<typename... Args>
void f(Args&&... args)
{
    for...(auto n : args) // error: expected '(' before '...' token
    {
        std::cout << n << std::endl;
    }
}

int main()
{
    auto v = std::vector{1, 2, 3};
    f(v, v, v);
}

See: https://godbolt.org/z/dEKsoqq8s

Why does the fold expression not apply to for loop?

xmllmx
  • 39,765
  • 26
  • 162
  • 323

2 Answers2

3

Because fold expressions are... expressions. A for loop is a statement. ... unpacking applies (with one or two exceptions) to expressions, not to statements.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Is the code snippet in the proposal a bug? see: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0330r8.html – xmllmx May 15 '21 at 03:01
  • @xmllmx: It's code from a proposal. A proposal that this proposal is *assuming* will be adopted and adopted with that syntax. – Nicol Bolas May 15 '21 at 03:12
  • 1
    @xmllmx what do you think the word "proposal" means? – Yakk - Adam Nevraumont May 15 '21 at 03:12
  • The cited proposal is accepted into C++23. @Yakk-AdamNevraumont – xmllmx May 15 '21 at 03:13
  • 2
    @xmllmx: ... and? What was accepted was a minor library change, adding a couple of literal suffixes. The reference to the `for...` proposal was an example of where the library change would be useful. The true proposal part is the wording section; everything else explains why it should be adopted. – Nicol Bolas May 15 '21 at 03:14
3

Below is from an authoritative C++ proposal [...]

A proposal is just a proposal. Finding an ISO C++ paper doesn't mean that the paper's contents were accepted into the ISO C++ Standard. The code samples you find in a proposal are not guaranteed to be valid, and sometimes authors intentionally use pseudocode to avoid unnecessary boilerplate.

for... is invalid C++ syntax. You can look at the latest Standard draft here to see what is actually in the language and what isn't.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416