我有一个基于boost :: Asio的使用回调的串行端口读取器,如下所示:
void received(const char *data, unsigned int len)
{
string s(data, len);
cout << s << endl;
}
int main()
{
try {
CallbackAsyncSerial serial("COM4", 115200);
serial.setCallback(received);
for(;;)
{
if(serial.errorStatus() || serial.isOpen()==false)
{
cerr<<"Error: serial port unexpectedly closed"<<endl;
break;
}
char c;
cin.get(c); //blocking wait for standard input
serial.write(&c,1);
}
quit:
serial.close();
} catch (std::exception& e) {
cerr<<"Exception: "<<e.what()<<endl;
}
}
如上所述,它可以编译并运行。现在我需要将其合并到现有的类中,所以我有:
void MyClass::received(const char *data, unsigned int len)
{
string s(data, len);
cout << s << endl;
}
int MyClass::main()
{
try {
CallbackAsyncSerial serial("COM4", 115200);
serial.setCallback(received); //COMPILE ERROR HERE
for(;;)
{
if(serial.errorStatus() || serial.isOpen()==false)
{
cerr<<"Error: serial port unexpectedly closed"<<endl;
break;
}
char c;
cin.get(c); //blocking wait for standard input
serial.write(&c,1);
}
quit:
serial.close();
} catch (std::exception& e) {
cerr<<"Exception: "<<e.what()<<endl;
}
}
但是,添加MyClass::received
会停止编译,并给我:
Error (active) E0415 no suitable constructor exists to convert from "void (const char *data, unsigned int len)" to "std::function<void (const char *, size_t)>"
我尝试将其调整为:
std::function< void() >received(const char *data, unsigned int len);
但是我看到同样的事情。 我在这里需要做什么?
答案 0 :(得分:1)
我需要将setCallback
行调整为:
serial.setCallback(
std::bind(&MyClass::received, this, std::placeholders::_1, std::placeholders::_2));