Created
April 12, 2014 03:19
-
-
Save bcrist/10517070 to your computer and use it in GitHub Desktop.
Menu Stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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