xmllmx
xmllmx

Reputation: 42379

Why does the fold expression not apply to for loop?

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?

Upvotes: 0

Views: 529

Answers (2)

Vittorio Romeo
Vittorio Romeo

Reputation: 93364

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.

Upvotes: 3

Nicol Bolas
Nicol Bolas

Reputation: 474136

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

Upvotes: 3

Related Questions