将非静态函数指针传递给另一个类

Pass a non-static function pointer to another class?

本文关键字:另一个 静态函数 指针      更新时间:2023-10-16

我有两个类,Win32和引擎。我试图将我的WindowProc函数从我的引擎类传递到Win32类。我知道类型定义WNDPROC被声明为:

typedef LRESULT(CALLBACK *WNDPROC)(HWND, UINT, WPARAM, LPARAM);

我的Win32标头声明为:

// Win32.h
#include <Windows.h>
class Win32
{
    public:
        Win32() {};
        ~Win32() {};
        void Initialize(WNDPROC);
    private:
        // Route messages to non static WindowProc that is declared in Engine class.
        static LRESULT CALLBACK MessageRouter(HWND, UINT, WPARAM, LPARAM);
};

我的Engine类被声明为:

// Engine.h
#include "Win32.h"
class Engine
{
    public:
        Engine() {};
        ~Engine() {};
        void Initialize();
    private:
        LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
        Win32* m_win32;
};

// Engine.cpp
#include "Engine.h"
void Engine::Initialize()
{
    m_win32 = new Win32;
    m_win32->Initialize(&WindowProc);  // How can I pass this function without making
                                       // it static or global.
}

我的Win32类已经有一个静态MessageRouter给WNDCLASSEX。所以我的问题是,我如何传递引擎::WindowProc函数类Win32不声明它的静态或全局?

您可以使用std::functionstd::bind()(在c++ 11中),或boost::function boost::bind()(在c++ 03中)。这两者在功能上是相当的,所以我将展示std::bind()的用法。

下面是如何基于std::function定义一个名为WNDPROC_FXN的类型别名:
typedef std::function<LRESULT CALLBACK (HWND, UINT, WPARAM, LPARAM)> WNDPROC_FXN;

这就是你在Win32类中使用它的方式:

class Win32
{
public:
    Win32() {};
    ~Win32() {};
    void Initialize(WNDPROC_FXN);
//                  ^^^^^^^^^^^
private:
    // Route messages to non static WindowProc that is declared in Engine class.
    static LRESULT CALLBACK MessageRouter(HWND, UINT, WPARAM, LPARAM);
};

这就是将成员函数绑定到this指针并传递给Win32::Initialize()的方法:

#include <functional>
// ...
void Engine::Initialize()
{
    using namespace std::placeholders;
    m_win32 = new Win32;
    m_win32->Initialize(std::bind(&Engine::WindowProc, this, _1, _2, _3 _4);
//                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

为了完整起见,还有一种方法可以使用语言结构来完成此操作。该实现使用指向成员函数的指针:

// Win32.h
#include <Windows.h>
class Engine;
class Win32
{
    public:
        Win32() {};
        ~Win32() {};
        void Initialize(LRESULT(CALLBACK Engine::* function)(HWND, UINT, WPARAM, LPARAM));
    private:
        // Route messages to non static WindowProc that is declared in Engine class.
        static LRESULT CALLBACK MessageRouter(HWND, UINT, WPARAM, LPARAM);
};
class Engine
{
    public:
        Engine() {};
        ~Engine() {};
        void Initialize();
    private:
        LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);
        Win32* m_win32;
};
void Engine::Initialize()
{
    m_win32 = new Win32;
    m_win32->Initialize(&Engine::WindowProc);  // How can I pass this function without making
                                               // it static or global.
}
int main(void)
{
    Engine engine;
    engine.Initialize();
    return 0;
}
相关文章: