#include // For iterator traits
#include // For assert
#include // For std::pair, std::make_pair
#include // For size_t
template
class EnumIterator {
public:
// Standard iterator traits
using value_type = std::pair<EnumType, const char*>;
using difference_type = std::ptrdiff_t;
using pointer = const value_type*; // Const for safety
using reference = const value_type&; // Const for safety
using iterator_category = std::forward_iterator_tag;
// Helper range class for STL compatibility and range-based for loops
template
class EnumRange {
public:
EnumRange(const EnumType* values, const char** names, size_t size)
: values_(values), names_(names), size_(size) {}
#include
#include // For std::find_if, std::transform
#include // For std::vector
#include // For std::string
// (Include the improved EnumIterator and EnumRange from above)
// Example enum
enum class Color { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
int main() {
// Arrays of enum values and names
const Color color_values[] = {Color::Red, Color::Green, Color::Blue, Color::Yellow};
const char* color_names[] = {"Red", "Green", "Blue", "Yellow"};
const size_t color_count = sizeof(color_values) / sizeof(color_values[0]);
code
// Create a range object
EnumRange<Color> colors(color_values, color_names, color_count);
// Showcase 1: Range-based for loop (modern and simple)
std::cout << "Showcase 1: Range-based for loop:\n";
for (const auto& [value, name] : colors) {
std::cout << name << " = " << static_cast<int>(value) << "\n";
}
// Showcase 2: Manual iteration with pre/post-increment and arrow operator
std::cout << "\nShowcase 2: Manual iteration:\n";
auto it = colors.begin();
while (it != colors.end()) {
std::cout << it->second << " has value " << static_cast<int>(it->first) << "\n";
it++; // Post-increment
}
// Showcase 3: Using STL algorithm (std::find_if)
std::cout << "\nShowcase 3: Finding 'Blue' with std::find_if:\n";
auto found_it = std::find_if(colors.begin(), colors.end(),
[](const auto& p) { return p.first == Color::Blue; });
if (found_it != colors.end()) {
auto [value, name] = *found_it;
std::cout << "Found: " << name << " = " << static_cast<int>(value) << "\n";
} else {
std::cout << "Not found\n";
}
// Showcase 4: Collecting into a vector with std::transform
std::cout << "\nShowcase 4: Collecting names into a vector with std::transform:\n";
std::vector<std::string> name_list;
std::transform(colors.begin(), colors.end(), std::back_inserter(name_list),
[](const auto& p) { return std::string(p.second); });
for (const auto& name : name_list) {
std::cout << "- " << name << "\n";
}
return 0;
}
// show me a more realistic example about Iterator
Assistant
Here's a realistic and practical example of using the EnumIterator and EnumRange classes in a real-world scenario: building a lookup table for HTTP status codes. This is a common use case in web applications, API development, and system logging, where you often need to map enum values (e.g., HttpStatusCode) to their human-readable names.
✅ Problem: Mapping HTTP Status Codes to Strings
In many web applications, you need to convert HTTP status codes (like 200, 404, 500) into their string equivalents ("OK", "Not Found", "Internal Server Error"). This mapping is essential for logging, user-facing messages, and API responses.
🛠 Solution: Use EnumIterator to Build a std::map
We'll define an enum class for HTTP status codes, create arrays of enum values and their corresponding names, and use EnumRange and EnumIterator to build a std::map that maps each status code to its name.
🧠 Key Concepts Demonstrated
Iterating over enum values using EnumRange and EnumIterator.
Building a lookup map from enum to string.
Using the iterator in a more complex scenario, not just for printing.
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
// Include the EnumIterator and EnumRange implementation from your code
enum class HttpStatusCode {
Ok = 200,
NotFound = 404,
InternalServerError = 500,
Created = 201,
Unauthorized = 401,
Forbidden = 403,
Accepted = 202
};
// Helper function to create a map from HttpStatusCode to string
std::map<HttpStatusCode, std::string> buildHttpStatusMap(
const HttpStatusCode* values,
const char** names,
size_t size) {
std::map<HttpStatusCode, std::string> statusMap;
EnumRange<HttpStatusCode> range(values, names, size);
for (const auto& [code, name] : range) {
statusMap[code] = name;
}
return statusMap;
}
int main() {
// Define enum values and names
const HttpStatusCode http_values[] = {
HttpStatusCode::Ok,
HttpStatusCode::NotFound,
HttpStatusCode::InternalServerError,
HttpStatusCode::Created,
HttpStatusCode::Unauthorized,
HttpStatusCode::Forbidden,
HttpStatusCode::Accepted
};
const char* http_names[] = {
"OK",
"Not Found",
"Internal Server Error",
"Created",
"Unauthorized",
"Forbidden",
"Accepted"
};
const size_t count = sizeof(http_values) / sizeof(http_values[0]);
// Build the lookup map
auto statusMap = buildHttpStatusMap(http_values, http_names, count);
// Example: Get the name for a given status code
HttpStatusCode code = HttpStatusCode::NotFound;
auto it = statusMap.find(code);
if (it != statusMap.end()) {
std::cout << "Status: " << it->second << " (" << static_cast<int>(code) << ")\n";
} else {
std::cout << "Unknown status code: " << static_cast<int>(code) << "\n";
}
// Example: Print all status codes and their names
std::cout << "\nAll HTTP Status Codes:\n";
for (const auto& [code, name] : statusMap) {
std::cout << name << " (" << static_cast<int>(code) << ")\n";
}
return 0;
}
🧪 Output
code
Status: Not Found (404)
All HTTP Status Codes:
OK (200)
Not Found (404)
Internal Server Error (500)
Created (201)
Unauthorized (401)
Forbidden (403)
Accepted (202)
🧩 Why This Is Realistic
Mapping is essential in APIs and logging systems.
Enums are used to represent well-known values, and the EnumIterator makes it easy to work with them.
The map is used in multiple places (logging, UI, response generation), showing real-world utility.
🔁 Additional Realistic Uses
You could also use EnumIterator to:
Validate input by checking if a given enum value exists.
Generate documentation or UI elements dynamically.
Process enums in bulk for testing or configuration.
📌 Summary
This example demonstrates how EnumIterator and EnumRange can be used to build a reusable, type-safe lookup structure for enums, which is a common and practical need in software development. It shows how to integrate the iterator into a real-world application, beyond simple iteration.