CLI11
CLI11 copied to clipboard
enums handling should use maps of enum value -> string
Maps are sorted containers, and enums are sorted too. When presenting users a set of choices, like verbosity level, for example, it makes sense to sort them by their value, while the library currently sorts them by their names.
#include <iostream>
#include <map>
#include <string>
// Define your enum type
enum class VerbosityLevel {
Low = 1,
Medium = 2,
High = 3,
};
// Custom comparison function for sorting enum values by their underlying value
struct EnumValueComparator {
template <typename T>
bool operator()(const T& lhs, const T& rhs) const {
return static_cast<int>(lhs) < static_cast<int>(rhs);
}
};
int main() {
// Create a map with custom comparison function
std::map<VerbosityLevel, std::string, EnumValueComparator> verbosityMap;
// Populate the map with enum values and their corresponding names
verbosityMap[VerbosityLevel::High] = "High";
verbosityMap[VerbosityLevel::Medium] = "Medium";
verbosityMap[VerbosityLevel::Low] = "Low";
// Iterate and print the sorted enum values and their names
for (const auto& entry : verbosityMap) {
std::cout << static_cast<int>(entry.first) << ": " << entry.second << std::endl;
}
return 0;
}