使用void函数作为回调,可从“ std :: function <void()>?

时间:2019-09-04 09:01:48

标签: c++ callback

我有一个基于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);

但是我看到同样的事情。 我在这里需要做什么?

1 个答案:

答案 0 :(得分:1)

rafix07

在评论中进行了回答

我需要将setCallback行调整为:

serial.setCallback(
    std::bind(&MyClass::received, this, std::placeholders::_1, std::placeholders::_2));