功能:术语不评估功能1149上的错误

时间:2015-01-06 00:57:36

标签: c++ std-function stdbind

我不明白这个错误。我试图使用std::function来传递成员函数作为参数。除了第四个和最后一个案例外,它的工作正常。

void window::newGame() {

}
//show options
void window::showOptions() {

}
 void window::showHelp() {

}
//Quits program
void window::quitWindow() {
    close();
}
void window::createMenu() {

    std::function<void()> newGameFunction = std::bind(&window::newGame);

    std::function<void()> showOptionsFunction = std::bind(&window::showOptions);


    std::function<void()> showHelpFunction = std::bind(&window::showHelp);


    std::function<void()> quitWindowFunction = std::bind(&window::quitWindow);
}

std::function的前三次使用没有错误,但在最终用法中我得到了以下内容:

Error 1 error C2064: term does not evaluate to a function taking 0 arguments第1149行的

functional

我只知道错误发生在线上,因为我拿出了所有其他的,这是唯一一个导致各种组合问题的人。

1 个答案:

答案 0 :(得分:1)

这些都不应该编译。成员函数很特殊:它们需要一个对象。所以你有两个选择:你可以用一个对象绑定它们,或者你可以让它们取一个对象。

// 1) bind with object
std::function<void()> newGameFunction = std::bind(&window::newGame, this);
                                                             //   ^^^^^^
std::function<void()> showOptionsFunction = std::bind(&window::showOptions, this);

// 2) have the function *take* an object
std::function<void(window&)> showHelpFunction = &window::showHelp;
std::function<void(window*)> quitWindowFunction = &window::quitWindow;

后两者可以被称为:

showHelpFunction(*this); // equivalent to this->showHelp();
quitWindowFunction(this); // equivalent to this->quitWindow();

最终取决于你function的用例,你想要这样做 - 但无论哪种方式,你肯定需要在某处window