Search code examples
c++std-functionstdbind

Functional: Term does not evaluate error on functional 1149


I don't understand the error in this. I'm trying to use std::functions to pass a member function as an argument. It works fine except for in the 4th and final case.

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);
}

No errors in the first 3 usages of std::function, however in the final usage I get the follow:

Error 1 error C2064: term does not evaluate to a function taking 0 arguments on line 1149 of functional.

I only know that the error occurs on the line because I took out all the other ones and that was the only one that caused any issue with a variety of combinations.


Solution

  • None of those should compile. Member functions are special: they need an object. So you have two choices: you can bind them with an object, or you can have them take an object.

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

    The latter two can be called like:

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

    It ultimately depends on your use-case for the functions which way you want to do it - but either way you definitely need a window in there somewhere!