Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用函数指针作为模板类的构造函数参数?_C++_Templates_Function Pointers - Fatal编程技术网

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))
);