Luc*_*cas 5 c++ function callback instance c++11
我仍然可以在C ++中找到自己的方式,并且遇到了问题。我有一个包含另一个类(不能从其继承)的实例成员的类,其中包括回调。我想将此回调注册到父类,但遇到困难。
经过一番挖掘之后,我了解了方法!=函数,因为一个实例方法隐式地希望它本身有一个实例(我可以描述它的最佳方式!),这std::bind是一个选择,但是当签名为时我无法使它起作用。不<void(void)>。
我还阅读了有关实现为接口的方法,类似于委托(我来自Swift背景),这也很有吸引力。
这是我要达到的目标的准系统版本:
class ChildClass
{
public:
std::function<int(int)> callback;
};
class MainClass
{
public:
ChildClass childClass;
MainClass()
{
this->childClass.callback = this->square;
}
private:
int square(int i)
{
return i * i;
}
};
Run Code Online (Sandbox Code Playgroud)
我知道类型不匹配会导致错误,但是我不知道如何使它们一起玩。
您可以使用lambda(带有 capture this)。
MainClass()
{
this->childClass.callback = [this](int i) { return this->square(i); };
}
Run Code Online (Sandbox Code Playgroud)
或者如果你想坚持std::bind:
MainClass()
{
using namespace std::placeholders;
this->childClass.callback = std::bind(&MainClass::square, this, _1);
}
Run Code Online (Sandbox Code Playgroud)
看看Bind 与 Lambda 的对比?我什么时候应该使用 std::bind?