为什么我不能在绑定中使用mem_fn函子?

Why Can't I use a mem_fn Functor in bind?

本文关键字:mem fn 函子 不能 绑定 为什么      更新时间:2023-10-16

我想将mem_fn参数传递给bind但编译器似乎不允许这样做。

例如,这工作正常:

accumulate(cbegin(foos), cend(foos), 0, bind(plus<int>(), placeholders::_1, bind(&foo::r, placeholders::_2)));

但是当我尝试使用mem_fn函子时,我得到了一页错误:

accumulate(cbegin(foos), cend(foos), 0, bind(plus<int>(), placeholders::_1, mem_fn(&foo::r)));
/

usr/include/c++/6/bits/stl_numeric.h:实例化 '_Tp std::accumulate(_InputIterator, _InputIterator, _Tp, _BinaryOperation( [其中 _InputIterator = __gnu_cxx::__normal_iterator>; _Tp = int; _BinaryOperation = std::_Bind(std::_Placeholder<1>, std::_Mem_fn(>]':
prog.cpp:20:102:从这里需要/
usr/include/c++/6/bits/stl_numeric.h:154:22:错误:调用"(std::_Bind(std::_占位符<1>, std::_Mem_fn(>( (int&, foo* const&('

嗯,很明显,第二个例子没有提到placeholders::_2。当accumulate使用两个参数调用函子时,将忽略第二个参数,并且代码正在尝试将intmem_fn返回的内部类的实例相加。

我建议你放弃所有这些bind游戏,并使用lambda:

accumulate(cbegin(foos), cend(foos), 0, 
[](int val, foo* f) { return val + f->r(); });

更清楚这里发生了什么。

要理解这一点,想想如果你只是把一个文字传递给bind的第3个参数意味着什么。例如,如果您已完成:

accumulate(cbegin(foos), cend(foos), 0, bind(plus<int>(), placeholders::_1, 13))

结果本来是size(foos) * 13的,因为plus会使用13作为每次迭代的补充。

accumulate(cbegin(foos), cend(foos), 0, bind(plus<int>(), placeholders::_1, mem_fn(&foo::r)))

不会编译,因为它试图将mem_fn(&foo::r)的结果作为plus的补充传递。既然不能转换成intplus就不能接受。但即使它可以转换为int,这不是你要找的,你想取第二个参数并调用它foo::r,将结果传递给plus。因此,我们知道我们需要看到,placeholders::_2语句中的某处使用,传达调用其r方法的第二个参数


我们需要绑定placeholders::_2绑定到一个函子,该函子将在其参数上调用r方法。绑定当然需要bind,但实际上bind可以采用一个方法,因为它是第一个参数。

也就是说,工作代码中的bind(&foo::r, placeholders::_2)语句在非嵌套形式下没有任何意义; 该函子甚至不需要 2 个参数! C++实际上有特殊的规则来处理嵌套在另一个bind中的bind,以便它们可以共享外部bind的占位符,以免无法将绑定参数传达给嵌套表达式:

如果存储的参数 arg 属于std::is_bind_expression<T>::value == trueT类型(例如,另一个bind表达式直接传递到对bind的初始调用中(,则bind执行函数组合:而不是传递绑定子表达式将返回的函数对象,而是急切地调用子表达式,并将其返回值传递给外部可调用对象。如果bind子表达式具有任何占位符参数,则它们将与外部bind共享。


在此表达式中使用mem_fn的唯一方法是将其结果传递给bind以传达placeholders::_2bind(mem_fn(&foo::r), placeholders::_2)这有效,但当简单的bind(&foo::r, placeholders::_2)就足够时,这是一个不必要的步骤。因此,生成此函子的最佳方法是使用您提供的语句:

accumulate(cbegin(foos), cend(foos), 0, bind(plus<int>(), placeholders::_1, bind(&foo::r, placeholders::_2)))

或者通过使用 lambda:

accumulate(cbegin(foos), cend(foos), 0, [](const int augend, const auto& addend) { return augend + addend.r(); } )