-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole-menu.h
75 lines (65 loc) · 1.59 KB
/
console-menu.h
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
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <exception>
namespace ConsoleMenu
{
class DifferentVectorSizesException : public std::exception
{
public:
const char* what() const override
{
return "Vector of menu items and functions for them should be equal";
}
};
template <typename... Args>
class ConsoleMenu
{
public:
ConsoleMenu(std::vector<std::string> const& menuItems, std::vector<void (*)(Args...)> const funcs)
: menuItems(menuItems), functions(funcs)
{
if (menuItems.size() != funcs.size())
throw DifferentVectorSizesException();
const_cast<std::vector<std::string>&>(this->menuItems).push_back("Exit");
}
void run(Args... args)
{
while (true)
{
std::cout << "// --- MENU --- //" << std::endl;
for (size_t i = 0; i < menuItems.size(); i++)
std::cout << i + 1 << " - " << menuItems[i] << std::endl;
size_t choice = getChoice();
if (choice == menuItems.size())
return;
functions[choice - 1](args...);
std::cout << std::endl;
}
}
private:
const std::vector<std::string> menuItems;
const std::vector<void (*)(Args...)> functions;
bool checkValidInput(size_t userChoice)
{
bool isValid = userChoice > 0 && userChoice <= menuItems.size();
if (isValid == false)
std::cout << "Invalid input!" << std::endl;
return isValid;
}
size_t getChoice()
{
size_t choice;
bool isValid = false;
while (isValid == false)
{
std::cout << ": ";
std::cin >> choice;
isValid = checkValidInput(choice);
}
std::cout << std::endl;
return choice;
}
};
}