试图将字符串传递给绑定函数 C++
Trying to pass a String to bound function C++
在此示例中,如何将字符串传递给绑定的 "handler" 函数?
// MyClass.h
class MyClass {
public:
MyClass(ESP8266WebServer& server) : m_server(server);
void begin();
void handler(String path);
protected:
ESP8266WebServer& m_server;
};
// MyClass.cpp
...
void MyClass::begin() {
String edit = "/edit.htm";
m_server.on("/edit", HTTP_GET, std::bind(&MyClass::handleFileRead(edit), this));
...
无论我尝试哪种方式,我都会得到:
error: lvalue required as unary '&' operand
lvalue required as unary '&' operand 表示需要一个变量来获取地址。对于您的方法:
void begin(const char* uri)
{
m_server.on(uri, HTTP_GET, std::bind(&MyClass::handler(&path), this));
}
路径未定义 - 因此在这种情况下路径不是可寻址变量。正如@Remy Lebeau 在上面的评论中提到的,如果你传入参数 uri - 那么你就有了一个有效的可寻址变量。
当你这样做时
std::bind(&MyClass::handleFileRead(edit), this)
你试图调用MyClass::handleFileRead(edit)
,并将结果的指针作为[=13]的参数=] 打电话。这当然是无效的,特别是因为函数没有 return 任何东西,也不是 static
成员函数..
你不应该调用函数,只需传递一个指向它的指针(并设置参数):
std::bind(&MyClass::handleFileRead, this, edit)
// ^ ^
// Note not calling the function here |
// |
// Note passing edit as argument here
在此示例中,如何将字符串传递给绑定的 "handler" 函数?
// MyClass.h
class MyClass {
public:
MyClass(ESP8266WebServer& server) : m_server(server);
void begin();
void handler(String path);
protected:
ESP8266WebServer& m_server;
};
// MyClass.cpp
...
void MyClass::begin() {
String edit = "/edit.htm";
m_server.on("/edit", HTTP_GET, std::bind(&MyClass::handleFileRead(edit), this));
...
无论我尝试哪种方式,我都会得到:
error: lvalue required as unary '&' operand
lvalue required as unary '&' operand 表示需要一个变量来获取地址。对于您的方法:
void begin(const char* uri)
{
m_server.on(uri, HTTP_GET, std::bind(&MyClass::handler(&path), this));
}
路径未定义 - 因此在这种情况下路径不是可寻址变量。正如@Remy Lebeau 在上面的评论中提到的,如果你传入参数 uri - 那么你就有了一个有效的可寻址变量。
当你这样做时
std::bind(&MyClass::handleFileRead(edit), this)
你试图调用MyClass::handleFileRead(edit)
,并将结果的指针作为[=13]的参数=] 打电话。这当然是无效的,特别是因为函数没有 return 任何东西,也不是 static
成员函数..
你不应该调用函数,只需传递一个指向它的指针(并设置参数):
std::bind(&MyClass::handleFileRead, this, edit)
// ^ ^
// Note not calling the function here |
// |
// Note passing edit as argument here