如何只传递绑定函数的第二个参数?

时间:2016-08-03 08:54:22

标签: c++ bind eventemitter handlers

我正在使用通用的EventEmitter实例:

EventEmitter mEventHandler;

所以我已经定义了这个绑定:

function<void(int, double)> onSetMin = bind(&ILFO::SetMin, this, placeholders::_2);
mEventHandler.on(kParamID, onSetMin);

on如:

mEventHandler.emit(paramID, someInt, someDouble);
如上所述,它是“通用的”,并设置2个参数。但是我的特定函数SetMin只需要一个参数(在这种情况下为someDouble):

void ILFO::SetMin(double min);

你如何从bind中传递第二个参数?

3 个答案:

答案 0 :(得分:2)

我认为更容易使用lambda来解决你的问题:

function<void(int, double)> onSetMin = [this](int dummy, double d) { SetMin(d); };
mEventHandler.on(kParamID, onSetMin);

答案 1 :(得分:0)

使用lambda而不是std::bind

mEventHandler.on(kParamID, [this] (int, double value) {
    SetMin(value);
});

std::bind的目的与您想要做的相反:它可以帮助您创建一个函数,从函数N中获取f个参数M其中{ {1}}通过将M > N的一些参数固定到给定值(或/并更改参数的顺序)。

答案 2 :(得分:0)

根据您可以使用的std::bind调用中的 C ++参考

  

未绑定的参数由占位符的_1,_2,_3 ...代替   名称空间std :: placeholders

https://en.cppreference.com/w/cpp/utility/functional/bind

using namespace std::placeholders;  // for _1, _2, _3...
// demonstrates argument reordering and pass-by-reference
int n = 7;
// (_1 and _2 are from std::placeholders, and represent future
// arguments that will be passed to f1)
auto f1 = std::bind(f, _2, 42, _1)