Custom object

I have a very simple menu class:

1
2
3
4
5
6
7
8
9
10
11
class Menu {
  int Option, numofOptions;
  void SwitchScreen() {
    Console::Clear(); //C++/CLI - clear console
    switch(Option) {
      case 1: //if option 1 do
      break;
      // until case numofOptions
    }
  }
};


I want a custom object of class Menu with variable integer numofOption. What am I going to do to get every case for each option?
I can't help you with C++/CLI... I can only give examples with normal C++.

What you could do is create a small struct to represent each option. Let's call this MenuOption. This will consist of two basic parts:
- a string to indicate what is printed on screen.
- a function callback to get called when that option is selected

1
2
3
4
5
6
7
8
#include <string>
#include <functional>  // C++11

struct MenuOption
{
    std::string name;
    std::function<void()> callback;
};


Now that we have each option outlined... we can add those options to a Menu class. The menu class can add these options dynamically by putting them in a resizable container, like a vector:

1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>

class Menu
{
    std::vector<MenuOption> options;

public:
    void addOption( std::string name, std::function<void> clbk )
    {
        MenuOption o = {name,clbk};
        options.push_back(o);
    }


Now we can call 'addOption' as many times as we want to add any number of options. To run it, we merely get a selection from the user, and call the appropriate callback depending on whatever option they selected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    void run()
    {
        // print the options to the user
        cout << "Please select an option:\n";
        for(unsigned x = 0; x < options.size(); ++x)
            cout << "  " << (x+1) << ") " << options[x] << '\n';

        // get the option they chose:
        int selection;
        cin >> selection;

        // assuming the option is valid (read:  I'm not doing that here!  You will
        //   want to check to make sure they didn't input something stupid.  I'm
        //   omitting that to keep the example simple)
        //
        // So yeah.. assuming it's valid... just call the appropriate callback:

        options[selection-1].callback();
    }
};



And there you have it. Now to use it, all you have to do is give it some options and call run:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void jumpUp()
{
    cout << "I'm jumping!" << endl;
}

void eatFood()
{
    cout << "Tasty Fresh!" << endl;
}

int main()
{
    // create your menu object
    Menu menu;

    // add some options
    menu.addOption( "Jump", &jumpUp );
    menu.addOption( "Eat", &eatFood );

    // do it
    menu.run();
}
I've been making a menu using highlight to select options and I stucked here. Thanks.
Topic archived. No new replies allowed.