|
| auto | DiffValues (const Value &base, const Value &target) -> ConfigDiff |
| | Compares two Value configurations and returns the differences.
|
| |
| auto | DiffFileFromDefaults (const Value &defaults, const Value &file_values) -> ConfigDiff |
| | Compares file configuration against defaults.
|
| |
| auto | DiffDefaultsFromFile (const Value &defaults, const Value &file_values) -> ConfigDiff |
| | Compares defaults against file configuration.
|
| |
| auto | JsonToValue (const nlohmann::json &json) -> Value |
| | Converts a nlohmann::json value to a cppfig::Value.
|
| |
| auto | ValueToJson (const Value &value) -> nlohmann::json |
| | Converts a cppfig::Value to a nlohmann::json value.
|
| |
| template<Serializer S> |
| auto | ReadFile (const std::string &path) -> StatusOr< Value > |
| | Helper to read a file into a Value tree via a serializer.
|
| |
| template<Serializer S> |
| auto | WriteFile (const std::string &path, const Value &data) -> Status |
| | Helper to write a Value tree to a file via a serializer.
|
| |
| template<IsSetting S> |
| constexpr auto | GetEnvOverride () -> std::string_view |
| | Helper to get environment override for a setting (empty if not defined).
|
| |
| template<IsSetting S> |
| auto | GetSettingValidator () -> Validator< typename S::value_type > |
| | Helper to get validator for a setting (always-valid if not defined).
|
| |
| auto | OkStatus () -> Status |
| | Returns an OK status.
|
| |
| auto | NotFoundError (std::string message) -> Status |
| | Returns a NotFound error status.
|
| |
| auto | InvalidArgumentError (std::string message) -> Status |
| | Returns an InvalidArgument error status.
|
| |
| auto | InternalError (std::string message) -> Status |
| | Returns an Internal error status.
|
| |
| auto | IsNotFound (const Status &status) noexcept -> bool |
| | Returns true if the status has code kNotFound.
|
| |
| auto | IsInvalidArgument (const Status &status) noexcept -> bool |
| | Returns true if the status has code kInvalidArgument.
|
| |
| auto | IsInternal (const Status &status) noexcept -> bool |
| | Returns true if the status has code kInternal.
|
| |
template<typename T >
requires std::is_arithmetic_v<T> |
| auto | Min (T min_value) -> Validator< T > |
| | Creates a validator that checks if a numeric value is at least min.
|
| |
template<typename T >
requires std::is_arithmetic_v<T> |
| auto | Max (T max_value) -> Validator< T > |
| | Creates a validator that checks if a numeric value is at most max.
|
| |
template<typename T >
requires std::is_arithmetic_v<T> |
| auto | Range (T min_value, T max_value) -> Validator< T > |
| | Creates a validator that checks if a numeric value is within [min, max].
|
| |
template<typename T >
requires std::is_arithmetic_v<T> |
| auto | Positive () -> Validator< T > |
| | Creates a validator that checks if a numeric value is positive.
|
| |
template<typename T >
requires std::is_arithmetic_v<T> |
| auto | NonNegative () -> Validator< T > |
| | Creates a validator that checks if a numeric value is non-negative.
|
| |
| auto | NotEmpty () -> Validator< std::string > |
| | Creates a validator that checks if a string is not empty.
|
| |
| auto | MaxLength (std::size_t max_len) -> Validator< std::string > |
| | Creates a validator that checks if a string length is at most max.
|
| |
| auto | MinLength (std::size_t min_len) -> Validator< std::string > |
| | Creates a validator that checks if a string length is at least min.
|
| |
| template<typename T > |
| auto | OneOf (std::vector< T > allowed_values) -> Validator< T > |
| | Creates a validator that checks if a value is one of the allowed values.
|
| |
template<typename T , typename Pred >
requires std::predicate<Pred, const T&> |
| auto | Predicate (Pred pred, std::string error_message) -> Validator< T > |
| | Creates a validator from a predicate function.
|
| |
| template<typename T > |
| auto | AlwaysValid () -> Validator< T > |
| | Creates an always-valid validator.
|
| |
C++20 compile-time type-safe configuration library.
cppfig is a header-only library for managing application configuration with:
- Compile-time type safety via C++20 concepts and templates
- Hierarchical configuration with dot-notation paths
- Environment variable overrides
- Validation with min/max ranges and custom validators
- Schema migration (automatic addition of new settings)
- Pluggable serialization (flat .conf by default, JSON opt-in, YAML/TOML possible)
Basic Usage
namespace settings {
struct AppName {
static constexpr std::string_view path = "app.name";
using value_type = std::string;
static auto default_value() -> std::string { return "MyApplication"; }
};
struct AppVersion {
static constexpr std::string_view path = "app.version";
using value_type = std::string;
static auto default_value() -> std::string { return "1.0.0"; }
};
struct ServerHost {
static constexpr std::string_view path = "server.host";
static constexpr std::string_view env_override = "SERVER_HOST";
using value_type = std::string;
static auto default_value() -> std::string { return "localhost"; }
};
struct ServerPort {
static constexpr std::string_view path = "server.port";
static constexpr std::string_view env_override = "SERVER_PORT";
using value_type = int;
static auto default_value() -> int { return 8080; }
}
};
struct LoggingEnabled {
static constexpr std::string_view path = "logging.enabled";
using value_type = bool;
static auto default_value() -> bool { return true; }
};
struct LoggingLevel {
static constexpr std::string_view path = "logging.level";
using value_type = std::string;
static auto default_value() -> std::string { return "info"; }
return cppfig::OneOf<std::string>({"debug", "info", "warn", "error"});
}
};
}
settings::AppName,
settings::AppVersion,
settings::ServerHost,
settings::ServerPort,
settings::LoggingEnabled,
settings::LoggingLevel
>;
int main() {
auto status = config.Load();
if (!status.ok()) {
std::cerr << "Failed to load config: " << status.message() << std::endl;
return 1;
}
std::string host = config.Get<settings::ServerHost>();
int port = config.Get<settings::ServerPort>();
status = config.Set<settings::ServerPort>(9000);
if (!status.ok()) {
std::cerr << "Invalid port: " << status.message() << std::endl;
}
status = config.Save();
}
Configuration schema holding all setting types.
Definition schema.h:59
Main configuration manager.
Definition configuration.h:83
Type-erased validator that can hold any validation function.
Definition validator.h:33
auto Range(T min_value, T max_value) -> Validator< T >
Creates a validator that checks if a numeric value is within [min, max].
Definition validator.h:113
Custom Types
To use custom types in configuration, specialize ConfigTraits:
struct DatabaseConfig {
std::string host;
int port;
};
template<>
return obj;
}
try {
return DatabaseConfig{
v["host"].Get<std::string>(),
static_cast<int>(v["port"].Get<int64_t>())
};
} catch (...) { return std::nullopt; }
}
static auto ToString(
const DatabaseConfig& c) -> std::string {
return c.host + ":" + std::to_string(c.port);
}
static auto FromString(std::string_view) -> std::optional<DatabaseConfig> {
return std::nullopt;
}
};
struct Database {
static constexpr std::string_view path = "database";
using value_type = DatabaseConfig;
static auto default_value() -> DatabaseConfig {
return DatabaseConfig{"localhost", 5432};
}
};
A self-contained, recursive value type for configuration data.
Definition value.h:26
static auto Object() -> Value
Creates an empty object value.
Definition value.h:133
Primary template for configuration type traits.
Definition traits.h:21
static auto Deserialize(const Value &value) -> std::optional< T >=delete
Deserializes a value from a Value node.
static auto ToString(const T &value) -> std::string=delete
Converts a value to a human-readable string.
static auto FromString(std::string_view str) -> std::optional< T >=delete
Parses a value from a string (e.g., from environment variables).
static auto Serialize(const T &value) -> Value=delete
Serializes a value to a Value node.
Testing
For unit testing, include the mock header:
mock_config.
SetValue<settings::ServerPort>(9000);
Mock implementation of configuration for testing.
Definition mock.h:46
void SetValue(typename S::value_type value)
Sets the value for a setting type (bypasses validation for testing).
Definition mock.h:75
GMock-compatible mock for IConfigurationProviderVirtual.
Definition mock.h:150
auto OkStatus() -> Status
Returns an OK status.
Definition status.h:52
Organizing Settings
You can organize related settings in namespaces or nested structs:
namespace settings::database {
struct Host {
static constexpr std::string_view path = "database.host";
using value_type = std::string;
static auto default_value() -> std::string { return "localhost"; }
};
struct Port {
static constexpr std::string_view path = "database.port";
using value_type = int;
static auto default_value() -> int { return 5432; }
};
}