Skip to content

Instantly share code, notes, and snippets.

@bcrist
Created April 12, 2014 03:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcrist/10517070 to your computer and use it in GitHub Desktop.
Save bcrist/10517070 to your computer and use it in GitHub Desktop.
Menu Stack
#include <stack>
#include <memory>
#include <cassert>
// Polymorphic base class for menus
class Menu
{
public:
// Common to all menus:
// (for example)
virtual void draw() = 0;
virtual void onMouseMove(int x, int y) = 0;
virtual void onMouseButton(int button, bool is_down) = 0;
// ... etc.
}
// A concrete menu class representing the main menu:
class MainMenu : public Menu
{
public:
MainMenu() {}
virtual void draw() { /* ... */ }
virtual void onMouseMove(int x, int y){ /* ... */ }
virtual void onMouseButton(int button, bool is_down) { /* ... */ }
// ...
}
// Of couse, normally you will have other menus as well.
int main(int argc, char** argv)
{
// std::stack is an adapter container that uses std::deque by default.
// You could just as easily use std::deque, std::vector, or std::list directly
// if you change push() to push_back(), top() to back(), and pop() to pop_back().
std::stack<std::unique_ptr<Menu>> menus;
Menu* m = new MainMenu();
menus.push(std::unique_ptr<Menu>(m));
assert(menus.top().get() == m);
menus.pop(); // the object pointed to by `m` is destroyed when the std::unique_ptr in the stack is removed.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment