For defining const config structs in child classes for something like analytics result storage, here are the main approaches:
Static Const Member Approach
This is often the cleanest for compile-time configuration:
class BaseAnalytics {
public:
struct Config {
std::string storage_path;
bool compress_results;
size_t max_file_size;
};
virtual const Config& getConfig() const = 0;
};
class NetworkAnalytics : public BaseAnalytics {
private:
static constexpr Config config_{
.storage_path = "/data/network/",
.compress_results = true,
.max_file_size = 1024 * 1024 * 100
};
public:
const Config& getConfig() const override {
return config_;
}
};
Template-Based Approach
If you want compile-time polymorphism and better optimization:
template<typename Derived>
class BaseAnalytics {
public:
const auto& getConfig() const {
return static_cast<const Derived*>(this)->config;
}
};
class NetworkAnalytics : public BaseAnalytics<NetworkAnalytics> {
public:
static constexpr struct {
std::string_view storage_path = "/data/network/";
bool compress_results = true;
size_t max_file_size = 104857600;
} config{};
};
Traits-Based Approach
For maximum flexibility and separation of concerns:
template<typename T>
struct AnalyticsTraits;
class BaseAnalytics {
public:
template<typename Derived>
static auto getConfig() {
return AnalyticsTraits<Derived>::config;
}
};
class NetworkAnalytics : public BaseAnalytics {};
template<>
struct AnalyticsTraits<NetworkAnalytics> {
static constexpr struct {
const char* storage_path = "/data/network/";
bool compress_results = true;
size_t max_file_size = 104857600;
} config{};
};
Key Considerations
Use constexpr when possible - This ensures compile-time initialization and better optimization.
Consider string storage - Use std::string_view or const char* for compile-time strings to avoid dynamic allocation.
Make configs immutable - Use const or constexpr to prevent accidental modification.
Think about inheritance - If child classes need to extend parent configs, consider composition:
struct BaseConfig {
std::string storage_path;
bool compress_results;
};
struct NetworkConfig : BaseConfig {
int packet_buffer_size;
bool enable_checksums;
};
The static const member approach is usually the best balance of simplicity and functionality for most use cases. The template approaches are better when you need zero runtime overhead or want to enforce configuration at compile time.