Generic programming: templates, concepts, and policies
What you will learn on this page
Section titled “What you will learn on this page”- 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 constexprand 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.
The problem: one logger, many programs
Section titled “The problem: one logger, many programs”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.
Requirements
Section titled “Requirements”| # | 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 |
Step 1: name what each part must do
Section titled “Step 1: name what each part must do”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).
// 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.
LogFormatsays: default-constructible, and has aconstmemberformatthat can be called with aLevel, astd::string_view, and astd::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::Guardrequires a nested type namedGuard. The conjunction then asks thatGuardcan be constructed fromL&. IfGuarddoes not exist, the whole concept is simply false, not an error. - The requirement is on what code does, not on every detail.
LogSinkasks thatsink.write(line)compiles for astd::string_view; it does not ask for a return type, because the logger ignores it. The logger then callswritewith exactly astd::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).
// 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 formatstatic_assert(!LogSink<PlainFormat>); // has no writestatic_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 LogSinkstatic_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.
Step 2: the policies
Section titled “Step 2: the policies”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).
// 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).
// 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).
// 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.
Step 3: the logger
Section titled “Step 3: the logger”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.
-
Each combination is its own class. When the demo names
AuditLog, which isLogger<JsonFormat, MemorySink, MutexLocked, Level::info>, the compiler first checks the four arguments against their concepts. Whenmainthen creates anAuditLogobject, the compiler makes a class just for those arguments:format_is aJsonFormat,locking_aMutexLocked, andsink_aMemorySink. -
Each level used gets its own
log.logis a template too, solog<Level::debug>andlog<Level::warning>are two separate functions. In each one,if constexpr (L >= Min)is worked out while compiling, and afalsebranch is thrown away. ForAuditLog(Minisinfo), the demo’s calls come out like this:Call in mainL >= 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 -
Inside a kept call, for
audit.error("disk\tfull"), in order:linestarts as an emptystd::string;format_.formatappends the JSON line to it. No lock is held yet, so other threads can format their own lines at the same time;guardis created. ForMutexLockedthis locks the mutex, waiting if another thread holds it. ForSingleThreadedit does nothing;sink_.writegets astd::string_viewofline. AMemorySinkcopies the characters into its vector, becauselineis about to go away;- at the closing brace the local objects are destroyed in reverse
order: first
guard, which unlocks the mutex, thenline.
-
log_withcalls the function only for a kept level. For a dropped level its body is empty, so the lambda is never called; in the demo,builtstays 0. For a kept level,std::invokecalls it once, its result becomesmessage, andlog<L>does the rest. The difference fromdebug(...)is when the text is made: an argument todebugis worked out before the call starts, even ifdebugthen does nothing. -
flushasks whether the sink hasflush. ForConsoleLog, whose sink is aStreamSink,s.flush()compiles, so the body takes the guard and callsstd::cout’s flush. ForAuditLog, whoseMemorySinkhas noflush, the requires-expression isfalse, andflushis 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 Formatinstead oftypename Format.LockingandMinhave defaults, so the common case is short. Minis a value, not a type. A non-type template parameter of enum type.log<L>testsL >= Minwithif 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 callformatat once, so a format with state, such as a shared buffer or a clock that usesstd::localtime, must make that safe itself. The formats here hold no data, so they are safe, likeconstfunctions of standard library types. log_withtakes 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 theif 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 tostd::string.flushuses an optional capability.if constexpr (requires(Sink& s) { s.flush(); })asks, at compile time, whether this sink hasflush. ForStreamSinkit does, and the call is compiled. ForMemorySinkthe branch is discarded, soflushcompiles and does nothing. The policy gets to have a feature without every policy being forced to have it. The price is silence: a sink whoseflushis misspelt, private, or takes an argument is simply never flushed. The tests guard against that withstatic_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, soLogger<PlainFormat, StreamSink>is exactly as big asStreamSink; 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
MemorySinkin is cheap, and aStreamSinkis 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).
#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");}Running it
Section titled “Running it”[info] service started[debug] cache warmedaudit lines: 2, debug messages built: 0{"level":"warning","message":"user \"kim\" failed to sign in"}{"level":"error","message":"disk\tfull"}routed: [warning] battery lowConsoleLogkeeps every level, so both the info and the debug line are printed, then flushed.AuditLogkeepsinfoand above. The debug call keeps nothing, and the expensive message passed tolog_withwas 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.
Step 4: what generic code costs
Section titled “Step 4: what generic code costs”Error messages
Section titled “Error messages”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
Loggerwere not satisfied, at the line naming the type. Clang added thatPutSinkdoes not satisfyLogSink, because it has no member namedwrite: 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 thatPutSinkhas no member namedwrite, at the line insidelogger.hppthat 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
PutSinkthat never logs compiles, because the member functions that callwriteare never instantiated. The mistake waits until someone first callsinfo. WithLogSink, the type itself is rejected. - Without constraints, a wrong type can compile and do the wrong
thing, as the
doubleprice 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.
Compile time and code size
Section titled “Compile time and code size”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
.cppfile, compiled once.JsonFormat::formatis defined inpolicies.cppfor 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-reportand Clang’s-ftime-traceshow where compile time goes. This page claims no compile times or sizes.
Readability
Section titled “Readability”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.
Testing
Section titled “Testing”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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 -> \u0001LLD_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).
// 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).
// 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).
// [[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
MemorySinkso that it no longer satisfiesLogSink, the test file stops compiling, which is a failed test. - The level tests check that dropped levels leave nothing and that
log_withdoes not call its function for a dropped level. - The thread test shares a
MutexLockedlogger between four threads and checks that all 1000 lines arrive whole. Its real check is ThreadSanitizer, which runs it in the tsan preset: withSingleThreadedswapped 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.
The design at a glance
Section titled “The design at a glance”class logging::Logger<Format, Sink, Locking, Min>
Format: LogFormat, Sink: LogSink, Locking: LockingPolicy
Data members
Format format_;no_unique_addressLocking locking_;no_unique_addressSink sink_;
Member functions
explicit Logger(Sink sink);Locking = SingleThreaded, Min = Level::debug by defaultvoid log<L>(std::string_view message);compiled to nothing when L is below Minvoid log_with<L>(MakeMessage&& make_message);a callable returning text; builds it only if L is keptvoid debug(std::string_view message);and info, warning, errorvoid flush();calls sink.flush() only if the sink has oneconst 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
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.
Common mistakes
Section titled “Common mistakes”- 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
.cppfile.
When the requirements change
Section titled “When the requirements change”- “Choose the format from a configuration file.” Then the format is
a run-time choice. Either give
Loggera format policy that holds a run-time choice, asCallbackSinkdoes 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
Minas 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
Section titled “Exercise”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;};- Write a concept
LogClockfor the clock: what doesTimestampedneed from it? - Constrain both parameters.
- Does
Timestamped<SomeClock, PlainFormat>satisfyLogFormat, so that it can be used as aLogger’s format? What would make it fail to? - Write
static_assertchecks 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 clockstatic_assert(!MakesTimestamped<FixedClock, MemorySink>); // a sink is not a formatThis 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.
- What it needs:
formatisconst, so it callsnow_text()on aconstclock, and appends the result to astd::string. The concept asks for exactly that: aconstnow_text()whose result converts tostd::string. It also asks forstd::default_initializable:Loggerdefault-constructs itsFormat, whichLogFormatrequires, so aTimestampedused as a format must default-construct its clock. The body converts the result to astd::stringbefore appending, so that it uses only what the concept promises. Appending the raw result asks for more: a type that converts both tostd::stringand toconst char*satisfies “convertible to string”, butout += xis ambiguous for it. Inneris constrained byLogFormat, the concept that already exists. Reusing it meansTimestampedaccepts any format, including anotherTimestamped.- Yes:
Timestampedhas theformatmemberLogFormatasks for, and it is default-initializable when its clock and inner format are, which the two constraints guarantee. The firststatic_assertafter the struct checks it. It would fail to ifformatwere notconst, or had a parameter list that aLevel, astd::string_view, and astd::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. - Both directions: the positive checks catch a concept that
rejects good types; the negative ones,
intas a clock and a sink as the inner format, catch a concept that accepts anything. TheMakesTimestampedhelper turns “this type cannot be named” into afalsethatstatic_assertcan 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.
Summary
Section titled “Summary”- A concept is a type’s contract: write one per policy, compose it
from standard concepts and requires-expressions, and test it with
static_assertin 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 constexprcompiles 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.