Po pierwsze to nie jest prawda że należy "sztywno rzutować na int". Typ enum class może mieć rodzica innego niż int. Często się tak robi szczególnie w embedded gdzie taki enum przechowuje np. maski lub wartości wpisywane na dany port. Oto prosty przykład:
#include <iostream>
#include <cstdint>
// AARRGGBB format..
enum class Color: uint32_t {
Window = 0x00808080,
Button = 0x80909090,
Menu = 0x40fAFAFA,
Font = 0x00000000
};
int main() {
// Pobranie typu z którego dziedziczy enum class Color
typename std::underlying_type<Color>::type x = 0x000000;
Color color = static_cast<Color>(x);
if(color == Color::Font) {
std::cout << "Wprowadzono kolor znaku.\n";
}
}
Co do translacji std::string -> enum class, rzeczywiście można to zrobić na wiele sposobów i mapa jest stosunkowo prosta.
Kontynuacja poprzedniego przykładu:
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <unordered_map>
// AARRGGBB format..
enum class Color: uint32_t {
Window = 0x00808080,
Button = 0x80909090,
Menu = 0x40fAFAFA,
Font = 0x00000000
};
void show_color_names(const std::unordered_map<std::string, Color>& color_map) {
std::cout << "Podaj nazwę z następującego zbioru [ ";
for(const auto& pr: color_map) {
std::cout << pr.first << ' ';
}
std::cout << " ]: ";
}
std::string read_color_name() {
std::string color_name;
std::cin >> color_name;
return color_name;
}
Color read_color_by_name() {
const static std::unordered_map<std::string, Color> str_to_color_map{
{"Window", Color::Window},
{"Button", Color::Button},
{"Menu", Color::Menu},
{"Font", Color::Font}
};
Color color_value;
for(;;) {
show_color_names(str_to_color_map);
auto color_name = read_color_name();
auto it = str_to_color_map.find(color_name);
if(it != str_to_color_map.cend()) {
color_value = (*it).second;
break;
}
std::cerr << "Nieprawidłowa nazwa. Spróbuj jeszcze raz.\n";
}
return color_value;
}
int main() {
Color color = read_color_by_name();
std::cout << "Wprowadzono kolor elementu o wartości hex: 0x"
<< std::hex << std::setw(8) << std::setfill('0')
<< static_cast<typename std::underlying_type<Color>::type>(color)
<< '\n';
}