Skip to content

Instantly share code, notes, and snippets.

@barasztamas
Created April 10, 2019 12:58
Show Gist options
  • Save barasztamas/14eed1ba7998aeda0259b32f5c698fc5 to your computer and use it in GitHub Desktop.
Save barasztamas/14eed1ba7998aeda0259b32f5c698fc5 to your computer and use it in GitHub Desktop.
C++ console menu template
#pragma once
#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;
template <class T>
using MenuFunction = void(*)(T&);
template <class T>
using TryCatchFunction = void(*)(MenuFunction<T>&, T&);
template <class T>
class Menu {
public:
Menu();
Menu(T);
void AddOption(string s, MenuFunction<T> f);
void Run();
void AddTryCatch(TryCatchFunction<T> f);
private:
T _a;
void menuWrite();
vector<string> _text;
vector<MenuFunction<T> > _function;
TryCatchFunction<T> _tryCatch;
bool _tryCatchExists;
};
template <class T>
Menu<T>::Menu()
{
_tryCatchExists=false;
};
template <class T>
Menu<T>::Menu(T a)
{
_tryCatchExists=false;
_a = a;
};
template <class T>
void Menu<T>::Run()
{
unsigned int n = 0;
do{
menuWrite();
cout << endl << ">>>>" ; cin >> n;
if(n>0&&n<=_function.size())
{
if(_tryCatchExists)
_tryCatch(_function[n-1],_a);
else
_function[n-1](_a);
}
}while(n!=0);
};
template <class T>
void Menu<T>::AddOption(string s, MenuFunction<T> f)
{
_text.push_back(s);
_function.push_back(f);
};
template <class T>
void Menu<T>::menuWrite()
{
cout << endl << endl;
cout << " 0. - Vege" << endl;
for(unsigned int i=0;i<_text.size();++i)
{
cout << setw(3)<<i+1 << ". - " << _text[i] << endl;
}
};
template <class T>
void Menu<T>::AddTryCatch(TryCatchFunction<T> f)
{
_tryCatch = f;
_tryCatchExists = true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment