0

I was utilizing a map of function pointers with different option values as follows in my main.cpp file for different menu items:

int main()
{
    while(true)
    {
        printMenu();
        int userOption = getUserOption();
        processMenu(userOption);
    }
    return 0;
}

where void processMenu(int userOption) is based on a menu of items. Thus, the function is reproduced below:

void processMenu(int userOption)
{
    std::map<int, void(*) ()> menu;
         
    menu[1] = printHelp;
    menu[2] = printStats;
    menu[3] = enterData;
    menu[4] = enterText;
    menu[5] = printNextTimestep;
    menu[6] = continue;
    menu[0] = badOptionPrint;
    
    if (userOption > 6 || userOption < 1)
        menu[0]();
    else
        menu[userOption]();
}

This map of function pointers worked fine for the purposes of utilizing it within the main.cpp file. However, I have recently created a header (.h) and corresponding C++ file (.cpp) for the Menu related functionality as refactoring. I am trying to replicate such functionality in the MenuMain.cpp file:

MenuMain.cpp:

void MenuMain::processMenu(int userOption)
{
    std::map<int, void(MenuMain::*) ()> menu;
         
    menu[1] = MenuMain::printHelp;
    menu[2] = MenuMain::printStats;
    menu[3] = MenuMain::enterData;
    menu[4] = MenuMain::enterText;
    menu[5] = MenuMain::printNextTimestep;
    menu[6] = MenuMain::continue;
    menu[0] = MenuMain::badOptionPrint;
    
    if (userOption > 6 || userOption < 1)
        menu[0]();
    else
        menu[userOption]();
}

Visual Studio gives the following error messages when hovering over the menu[0](); and menu[userOption]();:

expression preceding parentheses of apparent call must have (pointer-to-) function type.

I am trying to figure out if there may be a way to utilize the method pointer map within the class implementation .cpp file without upsetting the compiler. Now that the menu options are not being connected to the appropriate methods of the newly refactored MenuMain class (which is defined in the appropriate MenuMain.h file. Is there a way to get around utilizing function pointers and an analogous member pointer within the MenuMain class's implementation .cpp file, or is a map of method (or function) pointers not possible due to needing an instance of MenuMain to be created prior to a map of method pointers being available?

I have seen some ways to get around this are delegates and potentially creating a new design pattern that can take advantage of this (such as aggregation), but I am would like to keep this as simple as possible as only MenuMain will need this map of function pointers that points to the appropriate MenuMain methods.

qxzsilver
  • 522
  • 1
  • 6
  • 21

0 Answers0