Ivaylo Valchev
Ivaylo Valchev

Reputation: 10425

Syntax issue when populating an array with a fold expression

Yes, I can use std::initializer_list. Yes, even easier, I can do aggregate initialization. But how does this work? I can't seem to fold my head around C++17's fold expressions. There aren't enough examples out there.

Here's what I came up with:

template<class T, std::size_t N>
struct foo
{
    T arr[N];

    template<typename... Args>
    constexpr foo(Args&&... pack)
    {
        static_assert(sizeof...(pack) <= N, "Too many args");
        std::size_t i = 0;
        (arr[i++] = ...);
    }
};

int main()
{
    foo<int, 5> a(1, 2, 3, 4, 5);
}

EDIT: Compiling with latest Clang. Fold expressions are supported.

Live example: http://coliru.stacked-crooked.com/a/777dc32da6c54892

Upvotes: 17

Views: 3777

Answers (2)

Vaughn Cato
Vaughn Cato

Reputation: 64308

Since the comma operator is left-associative, you would ideally use a left unary fold:

(...,void(arr[i++] = pack))

The cast to void is to make sure that the built-in comma operator is used. In this case, the handedness doesn't actually matter.

Upvotes: 5

T.C.
T.C.

Reputation: 137425

You need to fold with the comma operator, which also solves the sequencing problem.

(void(arr[i++] = pack) , ...);

Upvotes: 15

Related Questions