1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#include <iostream>
#include <string>
struct Visitor {
virtual void visit (int&) = 0;
virtual void visit (std::string&) = 0;
virtual void visit (char& c) = 0;
};
struct ChooseVisitor : Visitor {
std::pair<int, bool> chosenInt;
std::pair<std::string, bool> chosenString;
std::pair<char, bool> chosenCharacter;
virtual void visit (int& num) override {
chosenInt.first = num;
chosenInt.second = true;
}
virtual void visit (std::string& str) override {
chosenString.first = str;
chosenString.second = true;
}
virtual void visit (char& c) override {
chosenCharacter.first = c;
chosenCharacter.second = true;
}
};
template <typename...> struct Menu;
template <typename T>
struct Menu<T> {
struct Option {
T item;
void accept (ChooseVisitor& visitor) {visitor.visit(item);}
};
Option* option; // Assume only one option for simplicity here.
ChooseVisitor choose() const {
ChooseVisitor visitor;
option->accept(visitor);
return visitor;
}
void insert (const T& t) {option = new Option{t};}
};
// A specialization for the Menu instances that will have submenus.
template <typename T, typename... Rest>
struct Menu<T, Rest...> { // Menu with T as its options type.
struct Option {
T item;
Menu<Rest...>* submenu; // Submenu with the first type in Rest... as its options type.
void accept (ChooseVisitor& visitor) {visitor.visit(item);}
};
Option* option;
ChooseVisitor choose() const {
// In reality there will be user input, of course. The user might not choose to enter a submenu,
// but instead choose from among the options in the current menu.
ChooseVisitor visitor;
if (option->submenu)
return option->submenu->choose();
else
option->accept(visitor);
return visitor;
}
void insert (const T& t, Menu<Rest...>* submenu = nullptr) {option = new Option{t, submenu};}
};
int main() {
Menu<int, std::string, char> menu;
Menu<std::string, char> submenu;
Menu<char> subsubmenu;
subsubmenu.insert('t');
submenu.insert ("", &subsubmenu);
menu.insert (0, &submenu);
const ChooseVisitor visitor = menu.choose();
if (visitor.chosenInt.second)
std::cout << "You chose " << visitor.chosenInt.first << ".\n"; // Do whatever with it.
else if (visitor.chosenString.second)
std::cout << "You chose " << visitor.chosenString.first << ".\n"; // Do whatever with it.
else if (visitor.chosenCharacter.second)
std::cout << "You chose " << visitor.chosenCharacter.first << ".\n"; // Do whatever with it.
}
|