C++ 如何使用函数指针作为模板类的构造函数参数?
我试图将函数指针作为参数传递给使用模板函数创建的对象,但在尝试这样做时出现以下错误:C++ 如何使用函数指针作为模板类的构造函数参数?,c++,templates,function-pointers,C++,Templates,Function Pointers,我试图将函数指针作为参数传递给使用模板函数创建的对象,但在尝试这样做时出现以下错误: error C2664: cannot convert argument 1 from 'void (__thiscall Northland::Sword::*)(Tecs::Entity&)' to 'void (__cdecl *)(Tecs::Entity&)' 这条线的起点是: // In Sword constructor m_entity.addComponen
error C2664: cannot convert argument 1 from
'void (__thiscall Northland::Sword::*)(Tecs::Entity&)' to
'void (__cdecl *)(Tecs::Entity&)'
这条线的起点是:
// In Sword constructor
m_entity.addComponent<Touchable>(&Sword::startTouch);
这里出现问题的原因是什么?是成员函数指针,而不是函数指针。所以你们也应该传递对象。 您可以为此使用
std::bind
,并在可触摸的情况下使用std::function
,而不是原始函数指针
m_entity.addComponent<Touchable>
(
std::bind(&Sword::startTouch, std::ref(sword_object))
);
m_entity.addComponent
(
标准::绑定(&剑::开始接触,标准::参考(剑对象))
);
在调用addComponent
时,您不提供实体作为第一个参数。此外,函数指针是一个成员函数,但是Touchable
构造函数需要一个正常的函数指针。(它们不能互换。)@leems对不起,我漏了一段代码。实体
调用另一个类的addComponent
方法,并将自身用作参数。
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&);
};
m_entity.addComponent<Touchable>
(
std::bind(&Sword::startTouch, std::ref(sword_object))
);