用折叠表达式填充数组时的语法问题 [英] Syntax issue when populating an array with a fold expression

查看:70
本文介绍了用折叠表达式填充数组时的语法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我可以使用 std :: initializer_list 。是的,甚至更容易,我可以进行聚合初始化。但这如何工作?我似乎无法将C ++ 17的fold表达式折叠起来。没有足够的例子。

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.

这是我想出的内容:

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);
}

编辑:使用最新的Clang进行编译。支持折叠表达式。

Compiling with latest Clang. Fold expressions are supported.

实时示例: http:/ /coliru.stacked-crooked.com/a/777dc32da6c54892

推荐答案

您需要使用逗号运算符进行折叠,

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

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

这篇关于用折叠表达式填充数组时的语法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆