一般来说,我可以将函数对象分配给函数指针吗?我想做这样的事情:
#include <iostream>
class Foo {
int num;
public:
Foo(int num_par) : num(num_par) {}
void operator()(int multiplier) {
std::cout << multiplier * num << std::endl;
}
};
int main() {
typedef void(*bar)(int);
Foo f(42);
bar b = f; // MSVC error
// ^ C2440: 'initializing' : cannot convert from 'Foo' to 'bar'
b(2); // wanted to print 84
}
如果那不可能,我想要一个专门用于 Windows 编程的替代方案,我想要的WindowProc
包含从本地数据设置到的状态信息WinMain
的主体(即不创建全局变量)。当分配给WNDCLASSEX
’s lpfnWndProc
成员。尽管std::function
解决了上面代码片段的问题:
std::function<void(int)> sf = f;
sf(2); // prints 84
它不适用于我的 WinAPI 案例:
class WindowProc {
int some_state;
public:
void set_some_state(int par);
LRESULT CALLBACK operator()(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
};
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow) {
HWND hWnd;
WNDCLASSEX wc;
WindowProc wp;
typedef LRESULT(CALLBACK *baz)(HWND, UINT, WPARAM, LPARAM);
std::function<baz> std_func = wp;
std::function<baz> std_binded_func = std::bind(&WindowProc::operator(), &wp);
// none of these compile:
wc.lpfnWndProc = wp; // #1
wc.lpfnWndProc = wp.operator(); // #2
wc.lpfnWndProc = &WindowProc::operator(); // #3. Wrong anyway because some_state's value is part of the instance, not the class
wc.lpfnWndProc = std_func; // #4. Wrong anyway because some_state's value is part of the instance, not the class
wc.lpfnWndProc = std_binded_func; // #5
// do stuff...
wp.set_some_state(some_runtime_number);
// ...do other stuff
}
MSVC 2013 错误:
1.) 错误 C2440:=
: 无法转换自WindowProc
to WNDPROC
2.) 错误 C3867:WindowProc::operator ()
:函数调用缺少参数列表;使用&WindowProc::operator ()
创建指向成员的指针
2 续)错误 C2440:=
: 无法转换自LRESULT (__stdcall WindowProc::* )(HWND,UINT,WPARAM,LPARAM)
to WNDPROC
3.) 与“2 续”相同
4.) 错误 C2440:=
: 无法转换自std::function<baz>
to WNDPROC
5.) 与 4 相同。
我怎样才能让它发挥作用?