std::bind() 参数列表中函子的执行顺序(可能与函数参数的求值顺序无关)

execution order of functors in std::bind() parameter list (maybe not related to evaluation order of function parameter)

本文关键字:参数 顺序 函数 std bind 执行 列表      更新时间:2023-10-16

我只是想知道并编写以下代码:(我不是在要求变通方法,我只是想知道bind()是否完美地处理了这个问题(。此外,我认为bind可以处理这个问题并为其定义顺序,但我不确定,或者可能只是参数求值顺序问题。

#include <functional>
#include <utility>
#include <iostream>
using namespace std;
class increment{
public : 
string operator()(int& x)
{
++x;
return string {"dumb_return_value"};
}
};
class multiply{
public : 
string operator()(int& x)
{
x = x * 2;
return string {"dumb_return_value"};
}
};
template <typename A, typename B>
class do_nothing{
public : 
void operator()(A , B)
{
return;
}
};

int main()
{
int x = 0;
increment increment_object;
multiply multiply_object;
do_nothing<string,string> do_nothing_object;
bind(do_nothing_object,bind(increment_object,ref(x)),bind(multiply_object,ref(x)))();
cout << x << endl;//output 2
x = 0;
bind(do_nothing_object,bind(multiply_object,ref(x)),bind(increment_object,ref(x)))();
cout << x << endl;//output 1
}

编译选项:std=c++1z因此,我使用引用语义来放大此处的差异。这些子函数incrementmultiply的执行顺序是什么?bind是谨慎地处理这个问题并定义一个顺序,还是依赖于特定于编译器的函数参数计算序列?如果std::bind()处理得很天意,请引用它,谢谢!

PS:我问这个问题的一个原因是:c++相当于java的andthen函数来复合新函数?

以本草案为参考。

func.bind.bind[20.10.9.1.3] 不指定何时计算绑定子表达式或其顺序。

它只是声明,如果要绑定的参数之一是绑定表达式结果,则外部绑定表达式的返回值使用调用内部绑定表达式的结果以及传递给外部绑定表达式的参数。 它没有提供何时评估这些值的排序信息;人们可能会假设它"必须"发生在外部绑定表达式传递参数之后,但(据我所知(我只能用常识得出结论,而不是从标准文本本身。