有什么方法可以在C ++中强制回调
想象一下,我有一些网络类 CNetwork
,它有一些叫做的方法: makeNetworkRequest(int requestCode)
。来自 makeNetworkRequest(int requestCode)
的响应当然可以在一段时间后调用此函数。我想要的是,当响应到来时,执行这样的代码,例如:
Hi,
Imagine I have some networking class CNetwork
which has some method called: makeNetworkRequest(int requestCode)
. The response from makeNetworkRequest(int requestCode)
can of course come some time later this function was called. What I want is that, when that response arrives, to execute such code for example:
void myApp::function1()
{
CMyButton button;
button.SetText(responseFromServer.text);
button.SetTextColor(responseFromServer.color);
}
我现在想要的是来自UI的用户可能正在使用不同的请求代码调用makeNetworkRequest - 以及基于此我可能想要执行不同的功能,例如执行function2而不是function1 - 我希望能够实现上面提到的功能。
The thing I want now is that the user from UI may be calling makeNetworkRequest with different request codes -- and based on that I may want to execute different functionality, e.g., for example execute function2 instead of function1 -- and I want to be able to achieve the functionality I mentioned above.
void myApp::function2()
{
CMyEdit edit;
edit.SetText(responseFromServer.text);
}
有很多方法可以实现您的目标。例如:
- 一个带有函数调用的switch语句,用于每种情况的硬编码
- 一种经典的,类似于C的回调机制,就像在Windows API(参见 EnumWindowsProc [ ^ ])。使用此方法,您必须使用静态方法,但
- 使用成员函数指针
- 使用多态,即传递实现包含该接口的接口的对象方法''
函数
''。不同的对象以不同的方式实现这种方法。- ...
There are really many ways to achieve what you intend to do. For instance:
- A switch statement with function calls hard-coded for every case
- A classical, C-like callback mechanism, like the one used in Windows API (see EnumWindowsProc[^]). With this approach, you have to use static methods, though
- Using member function pointers
- Using polymorphism, that is pass an object implementing the interface containing the method ''
function
''. Different objects implement such method in different ways.- ...
你可能想用 I / O完成端口 [ ^ ]
Windows套接字2.0:使用完成端口编写可扩展的Winsock应用程序 [ ^ ]
您可以使用 BindIoCompletionCallback [ ^ ],我想你会发现这篇文章有一些兴趣: IOCPNet - Ultimate IOCP [ ^ ]
祝你好运
Espen Harlinn
You would probably like to use I/O Completion Ports[^]
Windows Sockets 2.0: Write Scalable Winsock Apps Using Completion Ports[^]
You can use BindIoCompletionCallback[^], and I guess you''ll find this article of some interest:IOCPNet - Ultimate IOCP[^]
Best regards
Espen Harlinn
查看 std: :功能 [ ^ ]和相关的标题。
give a look to std::function[^] and related header.