C++ 在lambda函数内调用类方法在类方法内
我的类方法声明如下:C++ 在lambda函数内调用类方法在类方法内,c++,c++11,lambda,C++,C++11,Lambda,我的类方法声明如下: void sendCommandToBluetoothModule(String command, SendCommandToBluetoothModuleCallback callback); 其中SendCommandToBluetoothModuleCallback为: typedef void (*SendCommandToBluetoothModuleCallback)(String); 所以,我打这个电话: sendCommandToBluetoothMod
void sendCommandToBluetoothModule(String command, SendCommandToBluetoothModuleCallback callback);
其中SendCommandToBluetoothModuleCallback
为:
typedef void (*SendCommandToBluetoothModuleCallback)(String);
所以,我打这个电话:
sendCommandToBluetoothModule("AT\r\n", [](String response) -> void {
Serial.println(response);
});
一切都按预期进行。问题是:如果我试图调用另一个类成员函数,那么我应该捕获这个
。当我将最后一段代码更改为:
sendCommandToBluetoothModule("AT\r\n", [this](String response) -> void {
Serial.println(response);
});
我收到以下错误:
错误:没有用于调用的匹配函数
'BluePlotterClient::sendCommandToBluetoothModule(常量字符[5],
BluePlotterClient::setupBluetoothModule():)'
我需要做什么才能打这个电话(例如):
不能将带有捕获的lambda用作函数指针。捕获时,在lambda中添加一个不能包含在简单函数指针中的附加状态 要解决此问题,您可以像stl一样使用模板:
template<typename F>
void sendCommandToBluetoothModule(String, F callback) {
// things
}
void sendCommandToBluetoothModule(String, std::function<void(String)> callback) {
// things
}
该类可以保存任何可复制的函数,如对象。只有捕获列表为空的lambda才能转换为函数指针。您可以使用
std::function
而不是函数指针。@GuillaumeRacicot有很多很多嵌入式平台(以及GUI框架)都有自己的字符串类-不是每个人都使用std::string
void sendCommandToBluetoothModule(String, std::function<void(String)> callback) {
// things
}