Syntax issue when populating an array with a fold expression

删除回忆录丶 提交于 2019-12-05 15:21:13

问题


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


回答1:


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

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



回答2:


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.



来源:https://stackoverflow.com/questions/34569455/syntax-issue-when-populating-an-array-with-a-fold-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!