简体   繁体   English

如何使用折叠表达式扩展为初始化列表?

[英]How to expand into initializer list with fold expressions?

I would like to insert as many zeros into a vector as there are arguments to a variadic templated function (ie number of arguments zeros into a vector).我想在向量中插入尽可能多的零,因为 arguments 到可变参数模板化的 function (即向量中的 arguments 零的数量)。 I am trying to use fold expressions to achieve this and it works when using (vec.push_back(zeroHelper(args)), ...);我正在尝试使用折叠表达式来实现这一点,并且在使用(vec.push_back(zeroHelper(args)), ...); . .

What I do not understand: Why does it not work when I try to initialize the vector directly by "unfolding" into an initializer list like follows:我不明白的是:为什么当我尝试通过“展开”到初始化器列表中直接初始化向量时它不起作用,如下所示:
std::vector<int> vec = { (zeroHelper(args), ...) }; ? ?

Full source code:完整源代码:

template <typename T>
T zeroHelper (T a) { return T{0}; }

template<typename ...Args>
void printer(Args&&... args) {
    std::vector<int> vec; // = { (zeroHelper(args), ...) };
    (vec.push_back(zeroHelper(args)), ...);
    for (auto i : vec) {
        std::cout << i << '\n';
    }
}

int main()
{
    printer(1, 2, 3, 4);
    return 0;
}

And here's the source on OnlineGDB.这是 OnlineGDB 上的源代码。

Expected output:预期 output:

0 0
0 0
0 0
0 0

Output with the initializer list approach: Output 与初始化列表方法:

0 0

Why?为什么?

Because in因为在

std::vector<int> vec = { (zeroHelper(args), ...) };

the parentheses return only one element, the last one;括号只返回一个元素,最后一个; the comma operator discard the precedings.逗号运算符丢弃前面的内容。

You should write你应该写

std::vector<int> vec = { zeroHelper(args) ... };

to maintains all elements.维护所有元素。

In

(vec.push_back(zeroHelper(args)), ...);

the parentheses activate the folding, the comma discards all elements except the last one but the push_back() operation is applied to vec for every args... elements.括号激活折叠,逗号丢弃除最后一个之外的所有元素,但push_back()操作适用于每个args...元素的vec

Observe also that, using the discarding propriety of the comma operator, you don't need zeroHelper() at all还要注意,使用逗号运算符的丢弃特性,您根本不需要zeroHelper()

You can write你可以写

std::vector<int> vec { ((void)args, 0)... };

or或者

(vec.push_back(((void)args, 0)), ...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM