如何使用函数指针作为模板化类的构造函数参数?

时间:2014-11-20 09:55:14

标签: 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.addComponent<Touchable>(&Sword::startTouch);

addComponent&lt;&gt;()方法是这样的(省略了非相关的东西):

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)...);
    // ...
}

最后,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&);
};

这可能是问题的原因?

1 个答案:

答案 0 :(得分:1)

它是成员函数指针,而不是函数指针。所以你也应该传递对象。 您可以使用std::bind和Touchable使用std::function,而不是原始函数指针。

m_entity.addComponent<Touchable>
(
   std::bind(&Sword::startTouch, std::ref(sword_object))
);