Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 719
DeiDei Avatar asked Jan 02 '16 18:01

DeiDei


2 Answers

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

(void(arr[i++] = pack) , ...);
like image 69
T.C. Avatar answered Nov 12 '22 13:11

T.C.


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.

like image 31
Vaughn Cato Avatar answered Nov 12 '22 13:11

Vaughn Cato