c++ - 功能性 : Term does not evaluate error on functional 1149

标签 c++ std-function stdbind

我不明白其中的错误。我正在尝试使用 std::function 将成员函数作为参数传递。除了第 4 种也是最后一种情况外,它工作正常。

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 的前 3 次使用没有错误,但在最终使用中我得到以下信息:

错误 1 ​​error C2064:term does not evaluate to a function taking 0 arguments on line 1149 of functional

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

最佳答案

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

// 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!

关于c++ - 功能性 : Term does not evaluate error on functional 1149,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27790493/

相关文章:

c++ - 从虚拟堆栈评估可变参数

c++ - 为什么以 std::placeholders::_1 而不是 _0 开头?

c++ - glGenTextures 和 glGenSamplers 有什么区别?

c++ - 与 C++ 程序中的脚本通信

c++ - 是否可以使用 32 位操作系统创建 64 位程序

c++ - std::function 可以存储指向数据成员的指针吗?

c++ - 将相对函数指针作为参数传递

c++ - C++中std::bind与二元运算函数的使用

c++ - 从 boost::bind 移动到 std::bind:编译错误

c++ - 逗号运算符的右操作数无效 std::cout