c++ std::bind within function
c++ std::bind within function
我正在为输入编写一个事件系统,其中存储任何使用过的键的回调向量。所有这些模板都将是带有一个浮点数作为参数的成员函数,所以我为此使用 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)
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- C++错误:"error: int aaa::bbb is protected within this context"
- 传递给std::function template的template参数究竟代表什么
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- "no matching function for call to 'Vector::Vector'"错误
- 如何在向量中删除 std::function<void()>?
- 不断"Attempting to reference a deleted function"
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- "Warning: Comma within array index expression"但逗号分隔函数参数
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- c++ std::bind within function
- 解析" cannot define member function ... within .."