泛型std::函数成员
Generic std::function member
我有一个使用EnumWindows的类。因为这需要一个回调,所以我把它包装成一个漂亮的小工具类,类似于这样:
Class Tools
{
public:
template<typename WinFunctor>
std::vector<HWND> FindWindow(WinFunctor Functor);
private:
BOOL EnumWindowMsgProc(HWND hWnd);
static BOOL CALLBACK FreeWndProc(HWND hWnd, LPARAM lParam)
{
Tools* pThis = (Tools*)lParam;
return pThis->EnumWindowMsgProc(hWnd);
}
std::vector<HWND> m_Windows;
/*Need to store WinFunctor Here*/
}
BOOL Tools::EnumWindowMsgProc(HWND hWnd)
{
if(/*Call WinFunctor Member here*/)
{
m_Windows.push_back(hWnd);
}
return TRUE;
}
template<typename WinFunctor>
std::vector<HWND> Tools::FindWindow(WinFunctor Functor)
{
m_Windows.clear();
EnumWindows(FreeWndProc, (LPARAM)this);
return m_Windows;
}
/*Windows Callbacks must be free (not a class member),
so I define a static method (free) and forward to my
member function(not free)*/
WinFunctor示例:
bool EnumByWindowName(HWND WinHandle,const std::wstring& WinName)
{
wchar_t Temp[1024]{L' '};
GetWindowText(WinHandle, Temp, 1024);
if (std::wstring(Temp).compare(WinName.c_str()) == 0)
return true;
return false;
}
期望的接口示例
Tools ToolInst;
auto Windows=ToolsInst.FindWindow(EnumByWindowName(std::placeholders::_1,"Notepad-Untitled"));
我需要以某种方式将Functor存储为成员,以便我可以稍后在回调中调用它,但是我不能只是模板类,因为这将要求我每次想要搜索不同的窗口时创建一个新的工具实例(并且工具类包含比EnumWindows更多的函数)。Functor必须始终接受hWnd,但随后可以使用它想要的任何方式对该数据进行操作,并可以传递所需的其他参数(例如WindowName sting)。是否可以存储函子而不必每次都创建类的新实例。感谢您的帮助
解决方案
Class Tools
{
public:
typedef std::function<bool(HWND)> WinFunctor;
std::vector<HWND> FindWindow(const WinFunctor& Functor);
private:
BOOL EnumWindowMsgProc(HWND hWnd);
static BOOL CALLBACK FreeWndProc(HWND hWnd, LPARAM lParam)
{
Tools* pThis = (Tools*)lParam;
return pThis->EnumWindowMsgProc(hWnd);
}
std::vector<HWND> m_Windows;
WinFunctor m_WinFunctor;
}
BOOL Tools::EnumWindowMsgProc(HWND hWnd)
{
if(m_WinFunctor(hWnd))
m_Windows.push_back(hWnd);
return TRUE;
}
std::vector<HWND> Tools::FindWindow(const WinFunctor& Functor)
{
m_Windows.clear();
m_WinFunctor=Functor;
EnumWindows(FreeWndProc, (LPARAM)this);
return m_Windows;
}
接口:
auto Windows = m_Tools.FindParentWindow(std::bind(&WinEnumFunctors::EnumByWindowName, std::placeholders::_1, L"Some WindowName"));
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法