简体   繁体   English

折叠表达式的评估顺序

[英]Order of Evaluation for Fold Expressions

Fold expressions seem to be a nice way to apply a function to each element of a tuple. 折叠表达式似乎是将函数应用于元组的每个元素的好方法。 However, if the applied function has side effects, the order of function invocations might be an important concern. 但是,如果应用的函数具有副作用,则函数调用的顺序可能是一个重要的问题。

Consider: 考虑:

#include <iostream>

template<typename... Ts>
void printStuff(Ts... args)
{
    ( ([](auto&& v) { std::cout << v << " "; })(args), ... );
    std::cout << '\n';
}

int main()
{
    printStuff("hello", 42, 1.5f);
    // expected output: hello 42 1.5
}

This seems to work . 似乎有效

But is the order of evaluation for the lambdas guaranteed here or could I end up with the values being flipped around in the output? 但是这里保证lambda的评估顺序还是最终可能会在输出中翻转这些值? Does the answer change if I used a different operator for chaining the commands together? 如果我使用不同的运算符将命令链接在一起,答案是否会改变?

A right-fold over an operator expands like this: ... (arg0 op (arg1 op arg2)) . 对运算符的右... (arg0 op (arg1 op arg2))展开如下: ... (arg0 op (arg1 op arg2)) So while the parens help, they don't guarantee anything about the order of the individual elements. 因此,虽然parens帮助,但他们不保证个别元素的顺序。

Therefore, it's all left up to op . 因此,这一切都留给了op And the comma operator (which is distinct from commas separating function arguments), even pre-C++17, is a hard sequence point. 逗号运算符 (与逗号分隔函数参数不同),即使是前C ++ 17,也是一个硬序列点。 It ensures left-to-right evaluation with no cross-talk. 它确保从左到右的评估,没有串扰。

If you had instead used + , there would be no sequencing guarantees. 如果您使用+ ,则没有排序保证。 So it depends on the operator you use. 所以这取决于您使用的操作员。 C++17 added a few more operators that have strict sequencing guarantees ( << , for example). C ++ 17增加了一些具有严格排序保证的运算符(例如<< )。

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

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