gpt4 book ai didi

c++ - 对功能库 std::bind 中的语法感到困惑

转载 作者:行者123 更新时间:2023-11-27 23:35:45 31 4
gpt4 key购买 nike

#include <iostream>
#include <functional>
class Solver{
public:
void print(){
std::cout << "i solved" << std::endl;
}
};

class ThingHandler{
public:
void handleThing(Solver& solver){
std::cout << "i handled something " << std::endl;
solver.print();
}
};

class CantHandle{
public:
void needHelp(std::function<void(Solver&)> handleThing){
handleThing(); // how do i here pass Solver as a parameter?
}
};



int main() {
ThingHandler thingHandler;
CantHandle cantHandle;
Solver solver;
auto fp = std::bind(&ThingHandler::handleThing, thingHandler,solver);
cantHandle.needHelp(fp);
return 0;
}

在“CantHandle”类中,当我调用辅助函数时它要求提供一个参数。这是有道理的,因为被调用的函数是 handleThing,它将求解器的引用作为参数。但我似乎无法弄清楚类 ThingHandler 中的语法。不应该 handleThing 已经绑定(bind)了参数吗?我收到以下错误“不匹配调用‘(std::function) ()”

完整错误信息:

error: no match for call to ‘(std::function) ()’ 23 |
handleThing(); // how do i here pass Solver as a parameter? note: candidate: ‘_Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = void; _ArgTypes = {Solver&}]’ 685 | function<_Res(_ArgTypes...)>:: |
^~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usr/include/c++/9/bits/std_function.h:685:5: note: candidate expects 1 argument, 0 provided gmake[3]: * [CMakeFiles/funcObj.dir/build.make:63: CMakeFiles/funcObj.dir/main.cpp.o] Error 1 gmake[2]: [CMakeFiles/Makefile2:73: CMakeFiles/funcObj.dir/all] Error 2 gmake[1]: [CMakeFiles/Makefile2:85: CMakeFiles/funcObj.dir/rule] Error 2 gmake: * [Makefile:118: funcObj] Error 2

最佳答案

needHelp 方法需要一个带一个参数的函数,但您想传递一个不带参数的函数。改变这个:

void needHelp(std::function<void(Solver&)> handleThing){

void needHelp(std::function<void()> handleThing){

使用 lambda 而不是 bind 通常更容易编写和阅读,并且当您可以接受任何可调用时通常不需要使用 std::function:

#include <iostream>

struct Solver{
void print(){
std::cout << "i solved" << std::endl;
}
};

struct ThingHandler{
void handleThing(Solver& solver){
std::cout << "i handled something " << std::endl;
solver.print();
}
};

struct CantHandle{
template <typename F>
void needHelp(F f){
f();
}
};

int main() {
ThingHandler thingHandler;
CantHandle cantHandle;
Solver solver;
cantHandle.needHelp(
[&solver,&thingHandler](){
thingHandler.handleThing(solver);
}
);
return 0;
}

关于c++ - 对功能库 std::bind 中的语法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338193/

31 4 0
文章推荐: C++ 库链接问题
文章推荐: python - 如何解析在 标签下包含 和 标签的行的 HTML 表格?
文章推荐: html - 如何仅使用 CSS 设置