cppfig 0.1.0
Modern C++20 compile-time type-safe configuration library
Loading...
Searching...
No Matches
cppfig Namespace Reference

C++20 compile-time type-safe configuration library. More...

Namespaces

namespace  detail
 
namespace  testing
 

Classes

class  ConfigDiff
 Result of comparing two configurations. More...
 
class  ConfigSchema
 Configuration schema holding all setting types. More...
 
struct  ConfigTraits
 Primary template for configuration type traits. More...
 
struct  ConfigTraits< bool >
 
struct  ConfigTraits< double >
 
struct  ConfigTraits< float >
 
struct  ConfigTraits< int >
 
struct  ConfigTraits< std::int64_t >
 
struct  ConfigTraits< std::string >
 
struct  ConfigTraitsFromJsonAdl
 Helper to create ConfigTraits for types with nlohmann::json ADL. More...
 
class  Configuration
 Main configuration manager. More...
 
struct  ConfSerializer
 Flat key-value .conf serializer — the default, zero-dependency serializer. More...
 
struct  DiffEntry
 Represents a single difference between two configurations. More...
 
class  IConfigurationProvider
 CRTP base class for configuration providers. More...
 
class  IConfigurationProviderVirtual
 Virtual interface for type-erased configuration access. More...
 
struct  JsonSerializer
 JSON serializer using nlohmann::json. More...
 
class  Logger
 Simple logger that writes to stdout/stderr. More...
 
struct  MultiThreadedPolicy
 Thread policy for multi-threaded usage. More...
 
struct  SingleThreadedPolicy
 Thread policy for single-threaded usage (zero overhead). More...
 
class  Status
 A lightweight status object carrying an error code and message. More...
 
class  StatusOr
 A value-or-error type, similar to std::expected (C++23). More...
 
struct  ValidationResult
 Result of a validation operation. More...
 
class  Validator
 Type-erased validator that can hold any validation function. More...
 
class  Value
 A self-contained, recursive value type for configuration data. More...
 

Concepts

concept  HasJsonAdl
 Concept for types that have nlohmann::json ADL serialization.
 
concept  Serializer
 Concept for serializer types.
 
concept  IsSetting
 Concept for valid setting types.
 
concept  HasEnvOverride
 Concept for settings with environment variable override.
 
concept  HasValidator
 Concept for settings with custom validator.
 
concept  Configurable
 Concept constraining types that can be used as configuration values.
 
concept  ValidatorFor
 Concept for validator types.
 

Typedefs

template<IsSetting S>
using setting_value_type = typename S::value_type
 Helper alias to get the value type for a setting.
 

Enumerations

enum class  DiffType : std::uint8_t { Added , Removed , Modified }
 Type of change detected in a diff. More...
 
enum class  LogLevel : std::uint8_t { Info , Warning , Error }
 Log levels for configuration messages. More...
 
enum class  StatusCode : std::uint8_t { kOk = 0 , kNotFound , kInvalidArgument , kInternal }
 Error codes used by cppfig operations. More...
 

Functions

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.
 

Detailed Description

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

#include <cppfig/cppfig.h>
// Define settings as structs
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; }
static auto validator() -> cppfig::Validator<int> {
return cppfig::Range(1, 65535);
}
};
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"; }
static auto validator() -> cppfig::Validator<std::string> {
return cppfig::OneOf<std::string>({"debug", "info", "warn", "error"});
}
};
} // namespace settings
// Create schema type
using MySchema = cppfig::ConfigSchema<
settings::AppName,
settings::AppVersion,
settings::ServerHost,
settings::ServerPort,
settings::LoggingEnabled,
settings::LoggingLevel
>;
int main() {
// Create configuration manager (.conf format by default)
cppfig::Configuration<MySchema> config("config.conf");
// Load configuration (creates file with defaults if it doesn't exist)
auto status = config.Load();
if (!status.ok()) {
std::cerr << "Failed to load config: " << status.message() << std::endl;
return 1;
}
// Access values with compile-time type safety and IDE autocompletion!
std::string host = config.Get<settings::ServerHost>();
int port = config.Get<settings::ServerPort>();
// Set values with validation
status = config.Set<settings::ServerPort>(9000);
if (!status.ok()) {
std::cerr << "Invalid port: " << status.message() << std::endl;
}
// Save configuration
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<>
struct cppfig::ConfigTraits<DatabaseConfig> {
static auto Serialize(const DatabaseConfig& c) -> cppfig::Value {
auto obj = cppfig::Value::Object();
obj["host"] = cppfig::Value(c.host);
obj["port"] = cppfig::Value(c.port);
return obj;
}
static auto Deserialize(const cppfig::Value& v) -> std::optional<DatabaseConfig> {
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;
}
};
// If you have CPPFIG_ENABLE_JSON and nlohmann ADL functions instead:
// #include <cppfig/json.h>
// template<>
// struct cppfig::ConfigTraits<DatabaseConfig>
// : cppfig::ConfigTraitsFromJsonAdl<DatabaseConfig> {};
// Now define a setting using the custom type
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:

// Use MockConfiguration for in-memory testing
mock_config.SetValue<settings::ServerPort>(9000);
// Or use MockVirtualConfigurationProvider with GMock
EXPECT_CALL(mock, Load()).WillOnce(Return(cppfig::OkStatus()));
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; }
};
}
// Access: config.Get<settings::database::Host>()

Typedef Documentation

◆ setting_value_type

template<IsSetting S>
using cppfig::setting_value_type = typedef typename S::value_type

Helper alias to get the value type for a setting.

Enumeration Type Documentation

◆ DiffType

enum class cppfig::DiffType : std::uint8_t
strong

Type of change detected in a diff.

Enumerator
Added 
Removed 
Modified 

◆ LogLevel

enum class cppfig::LogLevel : std::uint8_t
strong

Log levels for configuration messages.

Enumerator
Info 
Warning 
Error 

◆ StatusCode

enum class cppfig::StatusCode : std::uint8_t
strong

Error codes used by cppfig operations.

Enumerator
kOk 
kNotFound 
kInvalidArgument 
kInternal 

Function Documentation

◆ AlwaysValid()

template<typename T >
auto cppfig::AlwaysValid ( ) -> Validator<T>

Creates an always-valid validator.

◆ DiffDefaultsFromFile()

auto cppfig::DiffDefaultsFromFile ( const Value defaults,
const Value file_values 
) -> ConfigDiff
inline

Compares defaults against file configuration.

Shows what default settings are missing or different in file:

  • ADDED: New settings in defaults not in file (schema migration)
  • REMOVED: Settings in file not in defaults (deprecated)
  • MODIFIED: Settings that will be overridden by file

◆ DiffFileFromDefaults()

auto cppfig::DiffFileFromDefaults ( const Value defaults,
const Value file_values 
) -> ConfigDiff
inline

Compares file configuration against defaults.

Shows what settings in the file differ from defaults:

  • ADDED: Settings in file not in defaults (possibly deprecated)
  • REMOVED: Settings in defaults not in file (will use default)
  • MODIFIED: Settings that differ from defaults

◆ DiffValues()

auto cppfig::DiffValues ( const Value base,
const Value target 
) -> ConfigDiff
inline

Compares two Value configurations and returns the differences.

Parameters
baseThe base configuration (e.g., defaults).
targetThe target configuration (e.g., file values).
Returns
A ConfigDiff containing all differences.

◆ GetEnvOverride()

template<IsSetting S>
constexpr auto cppfig::GetEnvOverride ( ) -> std::string_view
constexpr

Helper to get environment override for a setting (empty if not defined).

◆ GetSettingValidator()

template<IsSetting S>
auto cppfig::GetSettingValidator ( ) -> Validator<typename S::value_type>

Helper to get validator for a setting (always-valid if not defined).

◆ InternalError()

auto cppfig::InternalError ( std::string  message) -> Status
inline

Returns an Internal error status.

◆ InvalidArgumentError()

auto cppfig::InvalidArgumentError ( std::string  message) -> Status
inline

Returns an InvalidArgument error status.

◆ IsInternal()

auto cppfig::IsInternal ( const Status status) -> bool
inlinenoexcept

Returns true if the status has code kInternal.

◆ IsInvalidArgument()

auto cppfig::IsInvalidArgument ( const Status status) -> bool
inlinenoexcept

Returns true if the status has code kInvalidArgument.

◆ IsNotFound()

auto cppfig::IsNotFound ( const Status status) -> bool
inlinenoexcept

Returns true if the status has code kNotFound.

◆ JsonToValue()

auto cppfig::JsonToValue ( const nlohmann::json &  json) -> Value
inline

Converts a nlohmann::json value to a cppfig::Value.

◆ Max()

template<typename T >
requires std::is_arithmetic_v<T>
auto cppfig::Max ( max_value) -> Validator<T>

Creates a validator that checks if a numeric value is at most max.

◆ MaxLength()

auto cppfig::MaxLength ( std::size_t  max_len) -> Validator<std::string>
inline

Creates a validator that checks if a string length is at most max.

◆ Min()

template<typename T >
requires std::is_arithmetic_v<T>
auto cppfig::Min ( min_value) -> Validator<T>

Creates a validator that checks if a numeric value is at least min.

◆ MinLength()

auto cppfig::MinLength ( std::size_t  min_len) -> Validator<std::string>
inline

Creates a validator that checks if a string length is at least min.

◆ NonNegative()

template<typename T >
requires std::is_arithmetic_v<T>
auto cppfig::NonNegative ( ) -> Validator<T>

Creates a validator that checks if a numeric value is non-negative.

◆ NotEmpty()

auto cppfig::NotEmpty ( ) -> Validator<std::string>
inline

Creates a validator that checks if a string is not empty.

◆ NotFoundError()

auto cppfig::NotFoundError ( std::string  message) -> Status
inline

Returns a NotFound error status.

◆ OkStatus()

auto cppfig::OkStatus ( ) -> Status
inline

Returns an OK status.

◆ OneOf()

template<typename T >
auto cppfig::OneOf ( std::vector< T >  allowed_values) -> Validator<T>

Creates a validator that checks if a value is one of the allowed values.

◆ Positive()

template<typename T >
requires std::is_arithmetic_v<T>
auto cppfig::Positive ( ) -> Validator<T>

Creates a validator that checks if a numeric value is positive.

◆ Predicate()

template<typename T , typename Pred >
requires std::predicate<Pred, const T&>
auto cppfig::Predicate ( Pred  pred,
std::string  error_message 
) -> Validator<T>

Creates a validator from a predicate function.

◆ Range()

template<typename T >
requires std::is_arithmetic_v<T>
auto cppfig::Range ( min_value,
max_value 
) -> Validator<T>

Creates a validator that checks if a numeric value is within [min, max].

◆ ReadFile()

template<Serializer S>
auto cppfig::ReadFile ( const std::string &  path) -> StatusOr<Value>

Helper to read a file into a Value tree via a serializer.

◆ ValueToJson()

auto cppfig::ValueToJson ( const Value value) -> nlohmann::json
inline

Converts a cppfig::Value to a nlohmann::json value.

◆ WriteFile()

template<Serializer S>
auto cppfig::WriteFile ( const std::string &  path,
const Value data 
) -> Status

Helper to write a Value tree to a file via a serializer.