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

How to use function pointer as a constructor argument for a templated class?

本文关键字:参数 构造函数 函数 指针      更新时间:2023-10-16

我正在尝试将函数指针作为参数传递给使用模板化函数创建的对象的参数,但是当我尝试这样做时出现此错误:

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<>() 方法如下所示(省略不相关内容):

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

这里问题的原因可能是什么?

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

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