![](/img/trans.png)
[英]C++14: Generic lambda with generic std::function as class member
[英]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'\0'};
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擁有更多的功能)。函子必須始終接受hWnd,然后可以使用所需的任何值對該數據進行操作,並可以傳遞對其執行操作所需的其他arg(例如WindowName字符串)。無論如何,是否存在存儲函子,而不必每次都創建類的新實例。 謝謝你的幫助
解決方案如Piotr S.發布。
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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.