c++ std::bind within function

c++ std::bind within function

本文关键字:function within bind c++ std      更新时间:2023-10-16

我正在为输入编写一个事件系统,其中存储任何使用过的键的回调向量。所有这些模板都将是带有一个浮点数作为参数的成员函数,所以我为此使用 std::bind 和一个占位符。我在 Key 类中有一个函数,它将回调添加到相应的向量,我想在该函数中进行绑定,但我遇到了一个问题,我找不到有关如何解决它的任何信息。

Key 头文件具有以下用于添加回调的原型:

template <class T>
void addOnPressed(void toCall(float), T *callOn);

这就是函数的实际外观:

template <class T>
void Key::addOnPressed(void toCall(float), T *callOn) {
onPressed.push_back(std::move(std::bind(toCall, callOn, std::placeholders::_1)));
}

为了测试这一切,我制作了一个 Player 类,该类在构造上添加了一些回调,这个构造函数如下所示:

-Player(Texture2D Texture, int LayerIndex, Input &Input) : InputObj{ Texture, LayerIndex, Input } {
input.keyboard.getKey(KeyboardKey::A).addOnPressed<Player>(&Player::moveLeft, this);
input.keyboard.getKey(KeyboardKey::D).addOnPressed<Player>(&Player::moveRight, this);
input.keyboard.getKey(KeyboardKey::W).addOnPressed<Player>(&Player::moveUp, this);
input.keyboard.getKey(KeyboardKey::S).addOnPressed<Player>(&Player::moveDown, this);
};

所有这些都给了我以下错误:

C2664 'void Key::addOnPressed<Player>(void (__cdecl *)(float),T *)': cannot convert argument 1 from 'void (__cdecl Player::* )(float)' to 'void (__cdecl *)(float)

我猜我需要以某种方式告诉 addOnPressed 函数给定的函数指针来自类 T,我尝试使用错误消息中给出的语法,但我得到的只是语法错误。

错误消息非常明确,addOnPressed传递成员函数指针时,将非成员函数指针作为其第一个参数。

您可以将参数类型更改为成员函数指针,例如

template <class T>
void addOnPressed(void (T::* toCall)(float), T *callOn)