开发者

Connecting to Boost Signals2 signal with anonymous or lambda function

I am trying to do the following in order to receive a string from a boost signal and post it to the display. The following syntax is incorrect.

signal<void (const char*)>                      UserMessageEvent;

// connect anonymous boost function to display message box on user message event 
UserMessageEvent.connect(boost::bind(AfxMessageBox, _1));

If this were C# I would do the following, leading me to believe I want to use a lambda function to convert between the calling type of the signal and the type of the AfxMessageBox arguments. However it is not clear to me how to do this.

UserMessageEvent += (c) => MessageBox.Show((some const char to LPCSTR conversion)c);

Any s开发者_运维技巧uggestions?

Edit: The error given by msvc10 is error C2914: 'boost::bind' : cannot deduce template argument as function argument is ambiguous


I don't know how boost::bind behave in regard to default parameters.

Anyway, here is the syntax with lambda :

UserMessageEvent.connect( [](const char* message)
{
   // maybe need here a conversion to LPCWSTR ?
   AfxMessageBox(message);
});


AfxMessageBox has several overloads and default parameters, which makes your construct above ambigious. Write a small function taking exactly one LPCSTR, which forwards to AfxMessageBox, and bind that to the signal<>.

EDIT: As some people seem not to like what I provided above (why downvote without a comment?) here some clarifying code for what I wrote above:

int MyMessageBox(LPCSTR msg)
{
    return AfxMessageBox(msg);
}

UserMessageEvent.connect(boost::bind(MyMessageBox, _1));


AfxMessageBox is __stdcall function, to support such functions you need to define BOOST_BIND_ENABLE_STDCALL before #include:

#define  BOOST_BIND_ENABLE_STDCALL
#include <boost\bind.hpp>

int _tmain(int argc, _TCHAR* argv[])
  {
  boost::bind<int, LPCTSTR>(
    &AfxMessageBox, L"", 0, 0);
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜