Skip to content

Generic programming: templates, concepts, and policies

Difficulty: Advanced

Key concepts

  • generic programming
  • concept
  • requires-expression
  • constraint
  • policy-based design
  • policy
  • if constexpr
  • no_unique_address
  • template instantiation
  • compile-time choice
  • How to write concepts for the parts of a design, compose them, and test them with static_assert, including the cases that must fail.
  • How policy-based design builds one class from several independent choices, each a template parameter checked by a concept.
  • How if constexpr and a requires-expression let a template use an operation only when a type has it.
  • What generic code costs: error messages, compile time, code size, and readability, and how to keep those costs down.
  • When to choose a template and when a virtual function, for a design rather than a single function.

A company has a command-line tool, a server, and a set of tests, and all of them log. They need different things:

  • The command-line tool prints readable lines to the console, from one thread, and keeps debug lines while it is being developed.
  • The server writes JSON lines that a log collector can parse, from many threads at once, and must not pay for debug messages it never keeps.
  • The tests capture lines in memory and check them.

The choices are independent: how a line looks, where it goes, and whether threads share the logger. Every program knows all three when it is compiled. And logging is called very often, so a call that is disabled should cost nothing.

# Requirement Design consequence
R1 Format, destination, and thread safety can be chosen independently Three separate policies, not one class per combination
R2 A program that logs from one thread pays nothing for locking Locking is a policy, and the single-threaded one does nothing
R3 Messages below a minimum level cost nothing, including building the message when it is expensive The minimum level is a template parameter; an expensive message is passed as a function
R4 A wrong choice, such as a sink without write, is rejected where the logger type is named Each policy parameter is constrained by a concept
R5 One destination can still be chosen at run time, from configuration One sink policy holds a function chosen at run time
R6 Formats are tested on their own, and the logger is tested with each policy Policies are small types with no hidden dependencies

Before writing the logger, write down what it needs from each policy. That is a concept per policy:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

policies.hpp
// A format turns a level and a message into one line, appended to out.
// The logger calls it outside its lock, so under MutexLocked several
// threads may call format at once: a format with state must make that safe.
//
// How to read a concept: `template <typename F> concept LogFormat = ...;`
// is a yes-or-no question about a type F, answered by the compiler. Here
// the answer is yes only if both parts joined by && are true:
// 1. std::default_initializable<F>: an F can be made with no arguments,
// because the Logger creates its format that way (a plain member).
// 2. the requires-expression: the names inside requires( ... ) are
// pretend variables, never created; the compiler only checks that
// the statement in the braces would compile with them. Because
// `format` is a const reference, F's format member must be const.
// No return type is asked for: the logger ignores whatever format returns.
template <typename F>
concept LogFormat = std::default_initializable<F> &&
requires(const F& format, Level level, std::string_view message,
std::string& out) { format.format(level, message, out); };
// A sink takes finished lines. It may also have flush(); the logger
// calls it only if it exists.
// Two questions: can an S be moved (the logger's constructor moves the sink
// it is given into itself), and does sink.write(line) compile for a
// non-const sink and a std::string_view? write may change the sink, which
// is why the pretend `sink` is S& and not const S&.
template <typename S>
concept LogSink = std::move_constructible<S> && requires(S& sink, std::string_view line) {
sink.write(line);
};
// A locking policy has a Guard type: constructing a Guard from the
// policy holds whatever lock the policy has until the Guard is destroyed.
// Three questions, checked left to right:
// 1. can an L be made with no arguments (the logger creates one)?
// 2. `requires { typename L::Guard; }`: does L have a nested type Guard?
// 3. can that Guard be constructed from an L& (a non-const policy)?
// If L has no Guard at all, the answer is simply "no", not a compile error.
template <typename L>
concept LockingPolicy = std::default_initializable<L> && requires { typename L::Guard; } &&
std::constructible_from<typename L::Guard, L&>;
How this code works: checking a type against a concept

A concept is a question the compiler answers with true or false. Writing LockingPolicy<MutexLocked> asks it about one type. The parts joined by && are checked from left to right, and the first false ends the check: the parts after it are not looked at.

Here is LockingPolicy asked about three types. The first two are the site’s locking policies; the third, std::mutex, is one of the negative checks in the tests.

Part of LockingPolicy<L> SingleThreaded MutexLocked std::mutex
1. std::default_initializable<L> yes yes yes
2. requires { typename L::Guard; } yes yes no
3. std::constructible_from<typename L::Guard, L&> yes yes not checked
Answer true true false

For MutexLocked, part 1 holds because its only member, a std::mutex, can be made with no arguments. Part 3 holds because its Guard has the constructor Guard(MutexLocked& policy).

std::mutex fails at part 2: it has no nested type called Guard. That is not a compile error. Inside a concept, a requirement that would not compile just makes the answer false.

LogSink<int> fails the same way, one step later. An int can be moved, so std::move_constructible<int> is true. But sink.write(line) does not compile for an int, so the requires-expression is false, and so is the concept.

  • A concept is a contract for a type, the compile-time counterpart of an interface. LogFormat says: default-constructible, and has a const member format that can be called with a Level, a std::string_view, and a std::string& to append to. Nothing about a base class, and nothing about a return type, which the logger ignores.
  • Concepts compose with &&. Each one combines a standard concept from <concepts> (std::default_initializable, std::move_constructible, std::constructible_from, std::same_as) with a requires-expression listing operations that must compile.
  • A requires-expression can ask for a type. typename L::Guard requires a nested type named Guard. The conjunction then asks that Guard can be constructed from L&. If Guard does not exist, the whole concept is simply false, not an error.
  • The requirement is on what code does, not on every detail. LogSink asks that sink.write(line) compiles for a std::string_view; it does not ask for a return type, because the logger ignores it. The logger then calls write with exactly a std::string_view, so that it uses no more than the concept checked. Ask for what the template uses, no more, so that reasonable types are not rejected.

Concepts are code, so they are tested:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_logger.cpp
// The concepts are tested like any other code: the policies must satisfy
// them, and things that are not policies must not.
// static_assert(condition) is checked while compiling: if the condition is
// false, the build stops with an error. So these checks need no test run.
// LogFormat<PlainFormat> asks the concept's question about PlainFormat
// and gives true or false.
static_assert(LogFormat<PlainFormat> && LogFormat<JsonFormat>);
static_assert(LogSink<MemorySink> && LogSink<StreamSink> && LogSink<CallbackSink>);
static_assert(LockingPolicy<SingleThreaded> && LockingPolicy<MutexLocked>);
// The negative checks: ! turns "does not satisfy" into a true assertion.
static_assert(!LogSink<int>);
static_assert(!LogFormat<MemorySink>); // has no format
static_assert(!LogSink<PlainFormat>); // has no write
static_assert(!LockingPolicy<std::mutex>); // no Guard, though it can be made with no arguments
// A Logger with a wrong argument cannot even be named.
// MakesLogger<F, S> is true if Logger<F, S> is a valid type. Inside this
// requires-expression, a Logger whose arguments break its concepts makes
// the answer false instead of stopping the build, because F and S are
// this concept's own parameters.
template <typename F, typename S>
concept MakesLogger = requires { typename Logger<F, S>; };
static_assert(MakesLogger<PlainFormat, MemorySink>);
static_assert(!MakesLogger<PlainFormat, int>); // int is not a LogSink
static_assert(!MakesLogger<MemorySink, PlainFormat>); // arguments swapped
// The logger finds flush only if it exists, so a renamed or private flush
// would silently stop being called. This check makes that a failed build.
// It asks directly about StreamSink, not through a template parameter, so
// if sink.flush() stopped compiling, this line would be a compile error.
static_assert(requires(StreamSink& sink) { sink.flush(); });

The negative checks matter as much as the positive ones. A concept that accepts everything is as useless as an interface with no functions, and a typo in a requires-expression can make a concept accept nothing, or everything, without any error. The MakesLogger checks test R4 directly: Logger<PlainFormat, int> is not a type at all. A requires { typename ... } around it turns “does not compile” into a false that static_assert can test. That only works when the types are template parameters: outside a template, an invalid requirement is an ordinary compile error, not false. Hence the small MakesLogger concept, whose parameters let the check fail quietly.

A policy is a small type that supplies one piece of behaviour. Each one does one job, and knows nothing about the others. Building a class from several of them is called policy-based design.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

policies.hpp
// The two formats. Each appends one line of text to `out` and returns
// nothing. They hold no data, so the same object can be used from several
// threads at once, and an empty struct takes no space inside a Logger.
// The bodies are in policies.cpp, compiled once, not in this header.
// "[warning] disk 91% full": the level's name in brackets, a space, then
// the message exactly as given.
struct PlainFormat {
void format(Level level, std::string_view message, std::string& out) const;
};
// {"level":"warning","message":"disk 91% full"}, with the message escaped
// so that the line is valid JSON for any UTF-8 message. Bytes that are not
// UTF-8 pass through unchanged.
struct JsonFormat {
void format(Level level, std::string_view message, std::string& out) const;
};

The formats hold no data, so they are structs: there is no invariant to protect. JsonFormat escapes quotes, backslashes, and control characters, because a message such as user "kim" would otherwise break the line.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

policies.hpp
// The three sinks. Each has write(std::string_view), which LogSink asks
// for; only StreamSink also has flush().
// Keeps every line in memory: for tests, and for showing the output.
class MemorySink {
public:
// emplace_back builds a new std::string inside the vector from the
// view, so the sink keeps its own copy of the characters. It must: the
// view points into a string the logger destroys right after the call.
void write(std::string_view line) { lines_.emplace_back(line); }
[[nodiscard]] const std::vector<std::string>& lines() const noexcept { return lines_; }
private:
std::vector<std::string> lines_;
};
// Writes each line to a stream it does not own; the stream must outlive
// the sink.
class StreamSink {
public:
// Stores the stream's address (&out). A pointer, not a reference
// member, so the sink can be copied and assigned like a plain value; it
// never deletes the stream. std::cout lives for the whole program.
explicit StreamSink(std::ostream& out) : out_(&out) {}
// *out_ is the stream itself: print the line and end it with a newline.
void write(std::string_view line) { *out_ << line << '\n'; }
// Pushes any text the stream is still holding in its buffer out now.
void flush() { out_->flush(); }
private:
std::ostream* out_;
};
// Passes each line to a function chosen at run time: the one place where
// this compile-time design makes a run-time choice.
// std::function<void(std::string_view)> can hold any callable (here a
// lambda) that takes a string_view and returns nothing; which one is
// decided when the program runs. Calling it costs one indirect call.
class CallbackSink {
public:
// Takes the function by value, then moves it into the member, so a
// temporary lambda is moved in rather than copied. See the idiom
// reference for std::move.
explicit CallbackSink(std::function<void(std::string_view)> callback)
: callback_(std::move(callback)) {}
// Calls the stored function with the line. If the sink was given an
// empty std::function, this throws std::bad_function_call.
void write(std::string_view line) { callback_(line); }
private:
std::function<void(std::string_view)> callback_;
};

The sinks do hold data, and that data has rules: a StreamSink refers to a stream it does not own, and a MemorySink’s lines are read through a const accessor. So they are classes with private members. Only StreamSink has flush; the concept does not require it.

CallbackSink holds a std::function, which chooses where lines go at run time (R5). Policies do not force every choice to compile time: a policy can itself contain a run-time choice, at the cost of one indirect call per line for that policy only.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

policies.hpp
// For a logger used by one thread: the guard does nothing, and the
// compiler removes it.
struct SingleThreaded {
struct Guard {
// The parameter has no name because it is not used. It exists so
// that LockingPolicy's "Guard can be made from an L&" holds.
explicit Guard(SingleThreaded&) noexcept {}
};
};
// For a logger shared between threads: one line is written at a time.
// RAII: while a Guard object exists, its thread holds the mutex; any other
// thread that makes a Guard waits in the constructor until it is released.
class MutexLocked {
public:
class Guard {
public:
// Constructing lock_ locks the policy's mutex (waiting if another
// thread holds it). A nested class may use the enclosing class's
// private members, so Guard can reach mutex_.
explicit Guard(MutexLocked& policy) : lock_(policy.mutex_) {}
private:
// std::lock_guard unlocks in its destructor, so the mutex is
// released when the Guard is destroyed, even if an exception is
// leaving the function that made it.
std::lock_guard<std::mutex> lock_;
};
private:
// A std::mutex cannot be copied or moved, so neither can MutexLocked,
// nor a Logger that uses it.
std::mutex mutex_;
};

The locking policy is a small piece of RAII: constructing its Guard holds the lock, destroying it releases it. SingleThreaded::Guard does nothing, so in an optimized build no code remains for it (R2). MutexLocked owns a std::mutex, which cannot be copied or moved, so a logger that uses it cannot be either. That is correct: moving a logger that other threads are using would be a bug.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

logger.hpp
// A logger assembled from three independent policies and a minimum level,
// all chosen when the code is compiled:
// Format how a line looks (PlainFormat, JsonFormat)
// Sink where lines go (MemorySink, StreamSink, CallbackSink)
// Locking whether threads may share (SingleThreaded, MutexLocked)
// Min the lowest level kept; lower levels compile to nothing
//
// Each combination is a different type with no virtual calls.
// Thread safety: as the Locking policy says; formatting happens outside
// the lock, so a format must be safe to call from several threads at once
// (the formats here hold no data). Ownership: the logger owns
// its sink by value; a StreamSink inside refers to a stream it does not own.
//
// Reading the template header: `LogFormat Format` is short for "a type
// parameter Format that must satisfy LogFormat", so a wrong type is
// rejected where Logger<...> is named. `Level Min` is not a type but a
// value of the enum Level, fixed at compile time. `= SingleThreaded` and
// `= Level::debug` are defaults used when a program leaves them out.
template <LogFormat Format, LogSink Sink, LockingPolicy Locking = SingleThreaded,
Level Min = Level::debug>
class Logger {
public:
// The sink is taken by value and moved into sink_, so a caller can
// pass a temporary such as MemorySink{}. format_ and locking_ are not
// mentioned, so they are made with no arguments, which is why the
// concepts ask for std::default_initializable.
explicit Logger(Sink sink) : sink_(std::move(sink)) {}
// Logs one message at level L, chosen at compile time: a caller writes
// log<Level::info>("text"). Formats the line, then writes it under the
// lock. If format or write throws (for example std::bad_alloc), the
// exception passes to the caller; a lock already taken is still
// released, by the Guard's destructor.
template <Level L>
void log(std::string_view message) {
// `if constexpr` is decided while compiling, not while running. If
// L is below Min, the compiler throws the whole block away: this
// version of log<L> has an empty body and does no work at all.
// Enum class values compare by their order in Level, debug lowest.
if constexpr (L >= Min) {
std::string line; // starts empty; the format appends to it
format_.format(L, message, line); // outside the lock
// A local Guard object: it takes the lock here, and its
// destructor releases it at the closing brace of this block.
// `typename` tells the compiler that Locking::Guard names a
// type, which it cannot know before Locking is chosen.
const typename Locking::Guard guard(locking_);
// Passes a std::string_view, the type LogSink tested, rather than
// the std::string itself, so the logger uses only what it checked.
sink_.write(std::string_view{line}); // exactly what LogSink checks
}
}
// Builds the message only if level L is kept, so an expensive message
// costs nothing when its level is compiled out.
// make_message is anything callable with no arguments (usually a
// lambda) that returns something convertible to std::string. The caller
// names L, and the compiler works out MakeMessage from the argument:
// log_with<Level::debug>([&] { return build_report(); }).
// `MakeMessage&&` here accepts both a named lambda and a temporary one.
// The requires clause checks exactly what the body does: call it as a
// named object (MakeMessage&), and turn the result into a std::string.
template <Level L, typename MakeMessage>
requires std::invocable<MakeMessage&> &&
std::convertible_to<std::invoke_result_t<MakeMessage&>, std::string>
void log_with(MakeMessage&& make_message) {
if constexpr (L >= Min) {
// Only reached for a kept level: std::invoke calls the function,
// as make_message() would, and its result becomes the message.
const std::string message = std::invoke(make_message);
log<L>(message); // the std::string converts to a string_view
}
}
void debug(std::string_view message) { log<Level::debug>(message); }
void info(std::string_view message) { log<Level::info>(message); }
void warning(std::string_view message) { log<Level::warning>(message); }
void error(std::string_view message) { log<Level::error>(message); }
// Flushes the sink if it can be flushed; otherwise does nothing.
// The condition is a requires-expression used as a compile-time bool:
// true if s.flush() would compile for this Sink, false if not. For a
// false answer the block is discarded, so a sink without flush compiles.
void flush() {
if constexpr (requires(Sink& s) { s.flush(); }) {
// Locked like write, so a flush never runs during another write.
const typename Locking::Guard guard(locking_);
sink_.flush();
}
}
// For reading a MemorySink in tests. Not locked: call it only when no
// other thread is logging.
[[nodiscard]] const Sink& sink() const noexcept { return sink_; }
private:
// [[no_unique_address]] lets a member with no data (PlainFormat,
// SingleThreaded) take no bytes of its own. MutexLocked holds a mutex,
// so it still takes the mutex's space.
[[no_unique_address]] Format format_;
[[no_unique_address]] Locking locking_;
Sink sink_;
};
How this code works: Logger::log, log_with, and flush

Most of the decisions in Logger are made by the compiler, once per combination, not by the running program on each call.

  1. Each combination is its own class. When the demo names AuditLog, which is Logger<JsonFormat, MemorySink, MutexLocked, Level::info>, the compiler first checks the four arguments against their concepts. When main then creates an AuditLog object, the compiler makes a class just for those arguments: format_ is a JsonFormat, locking_ a MutexLocked, and sink_ a MemorySink.

  2. Each level used gets its own log. log is a template too, so log<Level::debug> and log<Level::warning> are two separate functions. In each one, if constexpr (L >= Min) is worked out while compiling, and a false branch is thrown away. For AuditLog (Min is info), the demo’s calls come out like this:

    Call in main L >= Min? What the compiled function does
    audit.debug(...) debug >= info: no nothing
    audit.log_with<Level::debug>(...) debug >= info: no nothing; the lambda is never called
    audit.warning(...) warning >= info: yes format, lock, write, unlock
    audit.error(...) error >= info: yes format, lock, write, unlock
  3. Inside a kept call, for audit.error("disk\tfull"), in order:

    • line starts as an empty std::string;
    • format_.format appends the JSON line to it. No lock is held yet, so other threads can format their own lines at the same time;
    • guard is created. For MutexLocked this locks the mutex, waiting if another thread holds it. For SingleThreaded it does nothing;
    • sink_.write gets a std::string_view of line. A MemorySink copies the characters into its vector, because line is about to go away;
    • at the closing brace the local objects are destroyed in reverse order: first guard, which unlocks the mutex, then line.
  4. log_with calls the function only for a kept level. For a dropped level its body is empty, so the lambda is never called; in the demo, built stays 0. For a kept level, std::invoke calls it once, its result becomes message, and log<L> does the rest. The difference from debug(...) is when the text is made: an argument to debug is worked out before the call starts, even if debug then does nothing.

  5. flush asks whether the sink has flush. For ConsoleLog, whose sink is a StreamSink, s.flush() compiles, so the body takes the guard and calls std::cout’s flush. For AuditLog, whose MemorySink has no flush, the requires-expression is false, and flush is an empty function.

So at run time a kept call does only the work in step 3, and a dropped one does nothing at all. There is no virtual call, and no check of the level while the program runs.

Reading the class, member by member:

  • The template header is the design. Four parameters, each constrained: LogFormat Format instead of typename Format. Locking and Min have defaults, so the common case is short.
  • Min is a value, not a type. A non-type template parameter of enum type. log<L> tests L >= Min with if constexpr, so for a level below the minimum the body is discarded: no formatting, no lock, no write (R3). What is left is an empty function, and with optimization the call to it usually disappears entirely.
  • The message is formatted outside the lock, and only the write is locked. Holding a lock for less time means threads wait less. The price is a rule for formats: under MutexLocked, several threads may call format at once, so a format with state, such as a shared buffer or a clock that uses std::localtime, must make that safe itself. The formats here hold no data, so they are safe, like const functions of standard library types.
  • log_with takes a function, not a string. A string argument is built by the caller before the call, even if the level is compiled out; a function is called only inside the if constexpr, so an expensive message is never built for a dropped level. Its constraint uses standard concepts: std::invocable<MakeMessage&>, because the body calls it as an lvalue, and a result convertible to std::string.
  • flush uses an optional capability. if constexpr (requires(Sink& s) { s.flush(); }) asks, at compile time, whether this sink has flush. For StreamSink it does, and the call is compiled. For MemorySink the branch is discarded, so flush compiles and does nothing. The policy gets to have a feature without every policy being forced to have it. The price is silence: a sink whose flush is misspelt, private, or takes an argument is simply never flushed. The tests guard against that with static_assert(requires(StreamSink& sink) { sink.flush(); }), so losing the feature breaks the build.
  • Empty policies take no space. [[no_unique_address]] (C++20) allows an empty member to share its address with another member, so Logger<PlainFormat, StreamSink> is exactly as big as StreamSink; a test checks it. MSVC ignores the standard attribute and has its own spelling, [[msvc::no_unique_address]], so code that must be small there needs a macro.
  • The logger owns its sink by value. Moving a MemorySink in is cheap, and a StreamSink is a pointer. There is no heap allocation for the logger itself and no virtual call anywhere.

Using it means naming a combination. Long template arguments are hard to read, so a program names the ones it uses with an alias, once:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
#include "level.hpp"
#include "logger.hpp"
#include "policies.hpp"
#include <iostream>
#include <string>
#include <string_view>
using namespace logging;
// Names for the combinations a program uses keep the long template
// arguments in one place.
// ConsoleLog leaves out the last two arguments, so it gets the defaults:
// SingleThreaded (no lock) and Level::debug (every level kept).
// AuditLog spells all four: JSON lines kept in memory, safe to share between
// threads, and only info and above kept.
using ConsoleLog = Logger<PlainFormat, StreamSink>;
using AuditLog = Logger<JsonFormat, MemorySink, MutexLocked, Level::info>;
int main() {
// The temporary StreamSink is moved into the logger. It points at
// std::cout, which lives until the program ends, so it never dangles.
ConsoleLog console(StreamSink{std::cout});
console.info("service started");
console.debug("cache warmed"); // kept: ConsoleLog's minimum is debug
console.flush(); // StreamSink has flush(), so this flushes std::cout
AuditLog audit(MemorySink{});
// Below AuditLog's minimum (info): in this logger, log<Level::debug>
// was compiled with an empty body, so the call does nothing.
audit.debug("not kept: below the minimum level");
// Counts how many times the message-building lambda really runs. [&]
// lets the lambda change `built` itself, not a copy. The level is
// dropped, so the lambda is never called and `built` stays 0.
int built = 0;
audit.log_with<Level::debug>([&] {
++built;
return std::string("an expensive debug message");
});
// R"( ... )" is a raw string: everything between the brackets is taken
// as written, so the double quotes around kim need no backslashes.
audit.warning(R"(user "kim" failed to sign in)");
// In an ordinary string literal, \t stands for one tab character. The
// JSON format writes it back as the two characters \t, as JSON requires.
audit.error("disk\tfull");
// Two lines kept (the warning and the error), and 0 messages built.
std::cout << "audit lines: " << audit.sink().lines().size()
<< ", debug messages built: " << built << '\n';
// sink() gives read-only access to the MemorySink inside the logger.
// Safe without the lock here, because no other thread is logging.
for (const std::string& line : audit.sink().lines()) std::cout << line << '\n';
// A sink chosen at run time, inside a logger whose other choices are
// fixed at compile time.
const bool to_console = true; // in a real program: from configuration
std::string kept;
// The lambda becomes the CallbackSink's std::function. It captures
// to_console and kept by reference ([&]); that is safe because `routed`
// is declared after them, so it is destroyed before they are.
Logger<PlainFormat, CallbackSink> routed(CallbackSink{[&](std::string_view line) {
if (to_console) {
std::cout << "routed: " << line << '\n';
} else {
kept += line;
}
}});
// Formatted by PlainFormat, then handed to the lambda, which prints
// "routed: [warning] battery low".
routed.warning("battery low");
}
Expected output
[info] service started
[debug] cache warmed
audit lines: 2, debug messages built: 0
{"level":"warning","message":"user \"kim\" failed to sign in"}
{"level":"error","message":"disk\tfull"}
routed: [warning] battery low
  • ConsoleLog keeps every level, so both the info and the debug line are printed, then flushed.
  • AuditLog keeps info and above. The debug call keeps nothing, and the expensive message passed to log_with was never built: the counter is still 0. The warning and the error are kept as JSON, with the quotes and the tab escaped.
  • The routed logger sends its line to a function chosen when the program runs.

A constraint moves an error to where the bad type is chosen, and names the rule it broke. Compiling Logger<PlainFormat, PutSink>, where PutSink has put instead of write, gave these results on this site’s build machine, with GCC 11.4 and Clang 14:

  • With the constraints, both compilers reported that the constraints of Logger were not satisfied, at the line naming the type. Clang added that PutSink does not satisfy LogSink, because it has no member named write: 10 lines in all. GCC gave the same reason in 23 lines, partly because it went on to report follow-on errors from the same statement.
  • Without them (each concept replaced by typename), both compilers reported that PutSink has no member named write, at the line inside logger.hpp that calls it, with the instantiation chain as notes: 7 lines from GCC and 11 from Clang.

So for a small template, a constraint does not always make the message shorter, and that is worth knowing. What it changes is where and what: the error points at the user’s line and names the broken requirement, instead of pointing into the library. The real gains are elsewhere:

  • Without constraints, a bad type can compile. A logger with PutSink that never logs compiles, because the member functions that call write are never instantiated. The mistake waits until someone first calls info. With LogSink, the type itself is rejected.
  • Without constraints, a wrong type can compile and do the wrong thing, as the double price on Templates: run-time versus compile-time polymorphism shows.
  • For deep templates, those calling other templates, an unconstrained error is reported at the bottom of a long chain. Constraints stop it at the top.

A class template is compiled again for each combination of arguments, in every source file that uses it, and only the member functions a program calls are compiled at all. Listing the demo’s symbols with nm -C in the gcc-debug build shows exactly that: ConsoleLog has info, debug, flush, and its constructor (its destructor is trivial, so none is emitted), but no warning or error, which the demo never calls on it; AuditLog has its own separate debug, warning, error, and log<L> for each level used, even the empty one.

So the costs grow with the number of combinations and the size of the template, and they fall on build time and binary size rather than on the running program:

  • Keep templates thin. Code that does not depend on the template arguments, such as JSON escaping, goes in an ordinary function in a .cpp file, compiled once. JsonFormat::format is defined in policies.cpp for that reason.
  • Use few combinations. Each program here uses one or two. A library with four kinds of policy and ten choices of each offers ten thousand combinations, and each one used is compiled separately.
  • Measure if build time matters. GCC’s -ftime-report and Clang’s -ftime-trace show where compile time goes. This page claims no compile times or sizes.

Logger<JsonFormat, MemorySink, MutexLocked, Level::info> says a lot in one line, and the error messages repeat it in full. A reader must also understand concepts, if constexpr, and requires-expressions to follow the class. Aliases help, and so does keeping the number of policies small: every policy is a new axis of variation that someone must understand, document, and test. Add a policy when a real program needs a different choice, not because one might.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_logger.cpp
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records
// a failure, printing both values, if they are not equal. Both come from
// the site's small test header, lld_test.hpp.
// A format is tested on its own: no logger, no sink, just text in and out.
LLD_TEST(plain_format_puts_the_level_in_brackets) {
std::string out;
// PlainFormat{} makes a temporary format object just for this call.
PlainFormat{}.format(Level::warning, "disk 91% full", out);
LLD_CHECK_EQ(out, std::string("[warning] disk 91% full"));
}
// The message holds four kinds of character that JSON needs escaped. In the C++
// literal below, \" is a double quote, \\ one backslash, \n a newline, and
// \x01 the control character with code 1. The expected line is a raw
// string, taken as written, and shows each one escaped:
// double quote -> \" newline -> \n
// backslash -> \\ code 1 -> \u0001
LLD_TEST(json_format_escapes_what_would_break_the_line) {
std::string out;
JsonFormat{}.format(Level::error, "say \"hi\"\\\n\x01", out);
LLD_CHECK_EQ(out, std::string(R"({"level":"error","message":"say \"hi\"\\\n\u0001"})"));
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_logger.cpp
// LLD_CHECK(condition) records a failure if the condition is false. It is
// used for the vectors below because LLD_CHECK_EQ prints both values, and
// a std::vector cannot be printed with <<.
// Minimum warning: one call at each level, and only the top two are kept.
LLD_TEST(levels_below_the_minimum_are_dropped) {
Logger<PlainFormat, MemorySink, SingleThreaded, Level::warning> log(MemorySink{});
log.debug("a");
log.info("b");
log.warning("c");
log.error("d");
const std::vector<std::string> expected{"[warning] c", "[error] d"};
// == on two vectors: same length, and equal element by element.
LLD_CHECK(log.sink().lines() == expected);
}
// Minimum info. The lambda `make` counts its own calls in `built`, which
// it captures by reference ([&]). A debug call must not run it; an info
// call must run it exactly once and keep one line.
LLD_TEST(a_dropped_level_does_not_build_its_message) {
Logger<PlainFormat, MemorySink, SingleThreaded, Level::info> log(MemorySink{});
int built = 0;
auto make = [&] {
++built;
return std::string("details");
};
log.log_with<Level::debug>(make);
LLD_CHECK_EQ(built, 0);
log.log_with<Level::info>(make);
LLD_CHECK_EQ(built, 1);
// std::size_t{1} is the number 1 in the unsigned type that size()
// returns, so both sides of the comparison have the same type.
LLD_CHECK_EQ(log.sink().lines().size(), std::size_t{1});
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_logger.cpp
// Four threads share one logger. With MutexLocked, every line arrives
// whole and none is lost. ThreadSanitizer checks this test for data races;
// with SingleThreaded instead, it reports them.
LLD_TEST(a_mutex_locked_logger_can_be_shared_between_threads) {
Logger<PlainFormat, MemorySink, MutexLocked> log(MemorySink{});
// This inner block exists to end the threads: a std::jthread joins
// (waits for its thread to finish) in its destructor, and the vector
// destroys all four at the closing brace.
{
std::vector<std::jthread> threads;
for (int t = 0; t < 4; ++t) {
// emplace_back starts a thread running this lambda. [&log, t]
// shares the one logger by reference, and copies t, so each
// thread keeps its own number even after the loop moves on.
// Each thread logs 250 lines: 4 x 250 = 1000 in all.
threads.emplace_back([&log, t] {
for (int i = 0; i < 250; ++i) log.info("thread " + std::to_string(t));
});
}
} // the jthreads join here
// Every thread has finished, so reading the sink without the lock is
// safe. `lines` is a reference to the vector inside the sink, not a copy.
const std::vector<std::string>& lines = log.sink().lines();
LLD_CHECK_EQ(lines.size(), std::size_t{1000}); // none lost
// A whole line is "[info] thread N" with one digit N: 6 + 1 + 6 + 1 + 1
// = 15 characters. Count the lines with exactly that shape.
std::size_t whole = 0;
for (const std::string& line : lines) {
if (line.size() == 15 && line.starts_with("[info] thread ")) ++whole;
}
LLD_CHECK_EQ(whole, std::size_t{1000});
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_logger.cpp
// [[no_unique_address]] lets empty policies take no space, so a logger is
// the size of its sink. GCC and Clang do this on Linux; MSVC ignores the
// standard attribute and needs [[msvc::no_unique_address]].
// StreamSink holds one pointer; PlainFormat and SingleThreaded hold
// nothing. So the whole logger should be exactly one pointer in size.
LLD_TEST(empty_policies_take_no_space) {
LLD_CHECK_EQ(sizeof(Logger<PlainFormat, StreamSink>), sizeof(StreamSink));
}
  • Policies are tested alone. A format is a function from a level and a message to text; testing it needs no logger and no sink (R6).
  • The concept checks run at compile time. If someone changes MemorySink so that it no longer satisfies LogSink, the test file stops compiling, which is a failed test.
  • The level tests check that dropped levels leave nothing and that log_with does not call its function for a dropped level.
  • The thread test shares a MutexLocked logger between four threads and checks that all 1000 lines arrive whole. Its real check is ThreadSanitizer, which runs it in the tsan preset: with SingleThreaded swapped in, a compiled copy of the test made ThreadSanitizer report data races.
  • The size test checks the [[no_unique_address]] claim on the compilers this site uses.

class logging::Logger<Format, Sink, Locking, Min>

Format: LogFormat, Sink: LogSink, Locking: LockingPolicy

Data members

  • Format format_; no_unique_address
  • Locking locking_; no_unique_address
  • Sink sink_;

Member functions

  • explicit Logger(Sink sink); Locking = SingleThreaded, Min = Level::debug by default
  • void log<L>(std::string_view message); compiled to nothing when L is below Min
  • void log_with<L>(MakeMessage&& make_message); a callable returning text; builds it only if L is kept
  • void debug(std::string_view message); and info, warning, error
  • void flush(); calls sink.flush() only if the sink has one
  • const Sink& sink() const noexcept; not locked

struct logging::PlainFormat

no data

Member functions

  • void format(Level level, std::string_view message, std::string& out) const;

struct logging::JsonFormat

no data; escapes the message

Member functions

  • void format(Level level, std::string_view message, std::string& out) const;

class logging::MemorySink

for tests

Data members

  • std::vector<std::string> lines_;

Member functions

  • void write(std::string_view line);
  • const std::vector<std::string>& lines() const noexcept;

class logging::StreamSink

does not own the stream

Data members

  • std::ostream* out_;

Member functions

  • explicit StreamSink(std::ostream& out);
  • void write(std::string_view line);
  • void flush();

class logging::CallbackSink

the run-time choice

Data members

  • std::function<void(std::string_view)> callback_;

Member functions

  • explicit CallbackSink(std::function<void(std::string_view)> callback);
  • void write(std::string_view line);

struct logging::SingleThreaded

Member functions

  • struct Guard; Guard(SingleThreaded&) does nothing

class logging::MutexLocked

Data members

  • std::mutex mutex_;

Member functions

  • class Guard; Guard(MutexLocked&) holds a lock on mutex_ while it exists
A logger template with three constrained policy parameters and a minimum level, and the policies it is built from

Templates or virtual functions, for a design

Section titled “Templates or virtual functions, for a design”

Templates: run-time versus compile-time polymorphism compares the two for one function. For a design built from several choices, the same questions decide, with more weight:

Question Policies (templates) Interfaces (virtual functions)
When is each choice known? When the program is compiled Any time, including from configuration
Can different choices be stored together? No: each combination is a different type Yes: one base type
Can a disabled call cost nothing? Yes, with if constexpr It still costs a call and a check
Can a policy add an optional feature? Yes, detected with a requires-expression Only by adding it to the interface, or by a cast
Where does the code live? In headers, compiled per combination In .cpp files, compiled once
What does a change to a policy’s header recompile? Every file that uses the template The files that include that header

Choose policies when the choices are known at compile time, are few, and are on a path that runs often enough that a call matters, like logging, containers, allocators, and numerical code. Choose interfaces when a choice comes from configuration or user input, when objects with different choices must live in one container, or when a stable binary interface matters more than the last nanosecond. Mix them where it helps, as CallbackSink does. The Strategy page shows both forms of a single choice.

  • Unconstrained templates. template <typename T> accepts anything, and the mistake shows up deep inside the template, or not at all.
  • Concepts that ask for too much, such as an exact return type the template ignores, or for too little, such as only the existence of a function. Ask for what the template uses, and test the concept with both kinds of type.
  • A concept that is never tested negatively. It may accept everything without anyone noticing.
  • Using more than the concept promises. If the template calls an operation the concept does not list, the concept is no longer the whole contract, and types that satisfy it can still fail to compile.
  • A policy for every possible choice. Each policy multiplies the number of types and the documentation; add one when a program needs it.
  • Building an expensive argument for a compiled-out level. The argument is evaluated before the call; pass a function instead.
  • Policies that depend on each other’s internals. A format that assumes a particular sink is not a separate policy, and the combinations stop being free.
  • Putting all the work in the template. Code that does not depend on the template parameters belongs in a .cpp file.
  • “Choose the format from a configuration file.” Then the format is a run-time choice. Either give Logger a format policy that holds a run-time choice, as CallbackSink does for sinks, or switch that axis to an interface. Keep the others as policies if they are still known at compile time.
  • “Each line needs a timestamp.” Add it as a format that wraps another format, so that existing formats do not change; the exercise does exactly that.
  • “Change the minimum level while the program runs.” A template parameter cannot change; add a run-time level check as well, and keep Min as the floor below which nothing is ever compiled.
  • “Ship the logger in a shared library with a stable binary interface.” Templates expose their whole implementation in headers, and each change recompiles users. PImpl, ABI, versioning, and compatibility covers the alternative.

Exercise: Add a concept constraint

This format puts the time in front of another format’s line. It works with suitable types, but it accepts anything, and a mistake shows up as an error inside format. This code is illustrative and was not compiled as shown; the answer was.

// A format that wraps another format: it writes the time, a space, and
// then whatever the inner format writes. Clock supplies the time as text;
// Inner is the format that writes the rest. Plain `typename` means any
// type is accepted here, so a wrong one is only noticed inside format.
template <typename Clock, typename Inner>
struct Timestamped {
void format(Level level, std::string_view message, std::string& out) const {
out += clock.now_text(); // ask the clock for the time, append it
out += ' ';
inner.format(level, message, out); // the inner format appends its line
}
// Both parts are held by value: a Timestamped owns its clock and its
// inner format, and makes them when it is made.
Clock clock;
Inner inner;
};
  1. Write a concept LogClock for the clock: what does Timestamped need from it?
  2. Constrain both parameters.
  3. Does Timestamped<SomeClock, PlainFormat> satisfy LogFormat, so that it can be used as a Logger’s format? What would make it fail to?
  4. Write static_assert checks that would catch a mistake in your concept, in both directions.
Show the explained answer
// A clock policy gives the current time as text.
// `{ clock.now_text() } -> std::convertible_to<std::string>;` is a compound
// requirement: the expression in braces must compile, and the type of its
// result must satisfy std::convertible_to<that type, std::string>. The
// pretend `clock` is const, so now_text() must be a const member.
template <typename C>
concept LogClock = std::default_initializable<C> && requires(const C& clock) {
{ clock.now_text() } -> std::convertible_to<std::string>;
};
// A format that puts the time in front of another format's line.
// Both parameters are now constrained: a type that is not a clock, or not
// a format, is rejected where Timestamped<...> is named.
template <LogClock Clock, LogFormat Inner>
struct Timestamped {
void format(Level level, std::string_view message, std::string& out) const {
const std::string time = clock.now_text(); // only what LogClock promises
out += time;
out += ' ';
inner.format(level, message, out);
}
// Empty members take no bytes of their own, as in Logger.
[[no_unique_address]] Clock clock;
[[no_unique_address]] Inner inner;
};
// For tests: always the same time, so the expected output never changes.
struct FixedClock {
[[nodiscard]] std::string now_text() const { return "12:00:00"; }
};
// Checked while compiling, in both directions: a real clock passes, and an
// int, which has no now_text(), does not.
static_assert(LogClock<FixedClock>);
static_assert(!LogClock<int>);
static_assert(LogFormat<Timestamped<FixedClock, PlainFormat>>); // a format made of formats
// Like MakesLogger in the tests: true if Timestamped<C, F> is a valid type,
// false (not a compile error) if an argument breaks a constraint.
template <typename C, typename F>
concept MakesTimestamped = requires { typename Timestamped<C, F>; };
static_assert(MakesTimestamped<FixedClock, JsonFormat>);
static_assert(!MakesTimestamped<int, PlainFormat>); // int is not a clock
static_assert(!MakesTimestamped<FixedClock, MemorySink>); // a sink is not a format

This answer was compiled with GCC 11.4 and Clang 14 with this site’s warnings as errors, and run with a MemorySink logger, printing 12:00:00 [warning] battery low.

  1. What it needs: format is const, so it calls now_text() on a const clock, and appends the result to a std::string. The concept asks for exactly that: a const now_text() whose result converts to std::string. It also asks for std::default_initializable: Logger default-constructs its Format, which LogFormat requires, so a Timestamped used as a format must default-construct its clock. The body converts the result to a std::string before appending, so that it uses only what the concept promises. Appending the raw result asks for more: a type that converts both to std::string and to const char* satisfies “convertible to string”, but out += x is ambiguous for it.
  2. Inner is constrained by LogFormat, the concept that already exists. Reusing it means Timestamped accepts any format, including another Timestamped.
  3. Yes: Timestamped has the format member LogFormat asks for, and it is default-initializable when its clock and inner format are, which the two constraints guarantee. The first static_assert after the struct checks it. It would fail to if format were not const, or had a parameter list that a Level, a std::string_view, and a std::string& cannot be passed to. A member without a default constructor cannot happen here, because both constraints already require one; only the unconstrained version could fail that way.
  4. Both directions: the positive checks catch a concept that rejects good types; the negative ones, int as a clock and a sink as the inner format, catch a concept that accepts anything. The MakesTimestamped helper turns “this type cannot be named” into a false that static_assert can check.

The [[no_unique_address]] members are optional, but with them a Timestamped<FixedClock, PlainFormat> is as small as an empty struct: sizeof printed 1 with both compilers.

  • A concept is a type’s contract: write one per policy, compose it from standard concepts and requires-expressions, and test it with static_assert in both directions.
  • Policy-based design builds a class from independent choices, each a constrained template parameter. Each combination is its own type, with no virtual calls.
  • if constexpr compiles away disabled work, such as a dropped log level; a requires-expression inside it lets a template use an optional feature of a type.
  • Empty policies cost no space with [[no_unique_address]].
  • Generic code costs build time, code size, and readability, and its errors are not always shorter. Keep templates thin, combinations few, and policies to the choices programs actually make.
  • Choose templates for compile-time choices on hot paths, and interfaces for run-time choices and heterogeneous collections; mix them where it helps.