[英]How to use function pointer as a constructor argument for a templated class?
I'm trying to pass a function pointer as an argument to an object that is created using a templated function, but I get this error when I try to do that: 我试图将函数指针作为参数传递给使用模板化函数创建的对象,但是在尝试执行此操作时出现此错误:
error C2664: cannot convert argument 1 from
'void (__thiscall Northland::Sword::*)(Tecs::Entity&)' to
'void (__cdecl *)(Tecs::Entity&)'
The line that originates this is this: 导致此的行是这样的:
// In Sword constructor
m_entity.addComponent<Touchable>(&Sword::startTouch);
The addComponent<>() method is like this (non-relevant stuff omitted): addComponent <>()方法是这样的(不相关的东西被省略):
template<class T, class... Params)
T& addComponent(Entity& entity, Params&&... params)
{
// ...
// Retrieves the next free memory portion
T* t = Pooler<T>::instance().getNext();
// Constructs the new T - this is where MSVC points when the error happens
t = new(t) T(std::forward<Params>(params)...);
// ...
}
Finally, the Touchable class looks like this: 最后,Touchable类如下所示:
class Touchable : public Tecs::Component
{
public:
Touchable(void(*touchFunc)(Tecs::Entity&))
: m_touchFunc(touchFunc)
{
}
void startTouch(Tecs::Entity& other)
{
(*m_touchFunc)(other);
}
private:
void(*m_touchFunc)(Tecs::Entity&);
};
What could be the cause of the problem here? 造成此问题的原因是什么?
It's member function pointer, not function pointer. 它是成员函数指针,而不是函数指针。 So you should pass object too.
因此,您也应该传递对象。 You can use
std::bind
for this and in Touchable use std::function
, instead of raw function pointer. 您可以为此使用
std::bind
,在Touchable中使用std::function
而不是原始函数指针。
m_entity.addComponent<Touchable>
(
std::bind(&Sword::startTouch, std::ref(sword_object))
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.