Implementation:ClickHouse ClickHouse EnumReflection
| Knowledge Sources | |
|---|---|
| Domains | Metaprogramming, Utilities |
| Last Updated | 2026-02-08 00:00 GMT |
Overview
A compile-time enum reflection utility that enables iteration over enum values and conversion to strings using magic_enum.
Description
This header provides compile-time reflection capabilities for C++ enums using the magic_enum library. It offers two main features: a `static_for` function that allows compile-time iteration over all enum values (useful for unrolling loops or generating switch statements), and automatic fmt formatter integration that enables printing enum values as their string names rather than numeric values.
The `static_for` template uses compile-time index sequences to iterate over enum values, allowing the callback function to use enum values as template parameters. This enables zero-overhead abstraction where the compiler can optimize away the iteration.
Usage
Use this implementation when you need to:
- Iterate over all values of an enum at compile time
- Generate code for each enum value (switch cases, lookup tables)
- Convert enum values to strings for logging or debugging
- Print enums in a human-readable format using fmt
- Implement generic algorithms that work with any enum type
Code Reference
Source Location
- Repository: ClickHouse
- File: base/base/EnumReflection.h
- Lines: 1-42
Signature
template <is_enum E, class F>
constexpr void static_for(F && f);
// Example: static_for<MyEnum>([](auto enum_value) { /* use enum_value as template param */ });
// Automatic fmt formatter for all enums
template <is_enum T>
struct fmt::formatter<T> : fmt::formatter<std::string_view>;
Import
#include <base/EnumReflection.h>
Usage Examples
#include <base/EnumReflection.h>
enum class Color { Red, Green, Blue };
// Iterate over all enum values at compile time
static_for<Color>([](auto color_value) {
// color_value can be used as a template parameter
constexpr Color c = color_value;
// Generate code for each color...
});
// Print enum as string using fmt
Color c = Color::Red;
fmt::print("Color: {}\n", c); // Prints "Color: Red"
// Use in logging
LOG_INFO(log, "Selected color: {}", Color::Green); // "Selected color: Green"
// Generate switch statement at compile-time
template <typename F>
void process_color(Color c, F && f) {
static_for<Color>([&](auto color_value) {
if (c == color_value)
f(color_value); // f receives compile-time constant
});
}