Skip to content

Strong types and API contracts

Difficulty: Advanced

Key concepts

  • strong type
  • phantom type
  • tag type
  • money type
  • minor unit
  • validated type
  • API contract
  • wide contract
  • narrow contract
  • deleted function
  • compile-time check
  • How to find the rules hidden in plain parameters, such as “this number is a customer, not an invoice” or “this amount is in cents”.
  • How to write one class template for every kind of id, and why it costs no space and copies like the number it holds.
  • How to give a money type only the operations that mean something, so that price * price or price * 1.5 does not compile.
  • How to check a rule once, when a value is made, so that every function receiving it can rely on it.
  • How to write down an API contract: what a function needs, what it promises, and what it throws, and how to choose where each rule is enforced.
  • How to test that misuse does not compile.

A small billing service turns orders into invoices. Its first version was written in an afternoon, and its main function looks like this:

The call compiles. It is also wrong, and nothing in the signature can tell anyone so. Collecting the bug reports from the first months gives a list:

  • B1. The invoice id and the customer id were passed the wrong way round, as in the call above. Both are std::uint64_t, so the compiler accepts either order. The wrong customer was billed.
  • B2. A caller passed 1999, meaning cents, where the function expected 19.99, meaning euros. The invoice was a hundred times too high.
  • B3. A caller passed the discount and the quantity in the wrong order: 10 items at 3% instead of 3 items at 10%.
  • B4. Totals were sometimes a cent out. double cannot hold most decimal fractions exactly, so 0.1 + 0.2 is not exactly 0.3, and the errors depend on the order of the additions.
  • B5. A quantity of 0 and a discount of 150 were accepted and produced an empty invoice and a negative total.
  • B6. When the service started billing in yen, a yen price was added to a euro invoice. The function has no idea which currency a double is in.
  • B7. Nobody remembered what true meant at the end of the call.

The requirements for the new version:

  • R1. An invoice belongs to one customer and is in one currency: euros, US dollars, or yen.
  • R2. Amounts are exact. Every total is a whole number of the currency’s smallest unit (a cent, or a yen), and no step loses one.
  • R3. A discount is a percentage from 0% to 100%, with up to two decimal places, such as 12.5%. Its rounding rule is written down.
  • R4. A total can be split into instalments that add up to exactly the total.
  • R5. Bad data, such as a zero quantity or a price in the wrong currency, is rejected with a clear message, and the invoice is left as it was.

Notice that only B4, B5, and B6 are about the data. B1, B2, B3, and B7 are about the call: values that were each correct ended up in the wrong place. Tests of invoice_total itself would not find them; the function did what it was told.

Before writing any type, list each plain value in the old API and write down what it really holds and how it can go wrong:

Parameter What it really is How it went wrong What prevents it
customer, invoice two different kinds of id swapped (B1) a different type for each kind
unit_price an amount in a currency, in some unit cents or euros (B2); currency (B6); rounding (B4) a money type with a currency, in whole minor units
quantity a count of items, at least 1 zero (B5); swapped (B3) a type whose constructor checks the rule
discount a percentage, 0 to 100 150 (B5); swapped (B3) a type whose factory checks the range
round_up one of two rounding rules unreadable (B7) a named rule (or none, if there is only one)

The right-hand column falls into three kinds of fix, and they are enforced at different times:

  1. Different types for different meanings. Two ids, or a count and a percentage, should not be interchangeable. Make each its own type, and a swap stops compiling. This is checked at compile time, for free.
  2. Only the operations that mean something. You can add two prices in the same currency, and multiply a price by a count. You cannot multiply two prices, or add a count to a price. Leave those operations out, and the mistakes stop compiling too.
  3. Rules about the value. “At least 1” and “0 to 100” depend on the number, which may come from a user at run time. The type checks them once, when the value is made, and every function that receives one can rely on it.

A type that wraps a plain value to give it a meaning of its own is called a strong type. The rest of the page builds one for each row.

Identity and equality wrote a MemberId class by hand. With many kinds of id, writing the same class for each one is repetitive, and the copies drift apart. One class template, with a tag type that only names the kind, replaces them all:

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

ids.hpp
// A number that names one thing of one kind. Tag is a type that is only
// declared, never defined or created; it exists only so that
// Id<CustomerTag> and Id<InvoiceTag> are different types.
// `template <typename Tag>` makes this a pattern for classes, not one class:
// the compiler writes a separate Id class for each Tag it is used with.
// The body never mentions Tag; its only job is to keep those classes apart.
template <typename Tag>
class Id {
public:
// `explicit`: a plain number becomes an Id only when the code says so,
// as in CustomerId{42}. There is no default constructor (no Id()), so
// every Id holds a number someone chose. constexpr lets an Id be made
// at compile time, and noexcept says making one never throws.
constexpr explicit Id(std::uint64_t value) noexcept : value_(value) {}
// The number itself, for printing or storing. Reading it is explicit,
// so an Id never turns back into a number by accident either.
[[nodiscard]] constexpr std::uint64_t value() const noexcept { return value_; }
// `<=>` (the "spaceship" operator), defaulted, compares the numbers, and
// from it the compiler also provides ==, !=, <, <=, > and >=. Both
// parameters are the same Id type, so an InvoiceId cannot be compared
// with a CustomerId. No other operator is declared, so ids cannot be
// added or multiplied. `friend` lets it be written inside the class.
friend constexpr auto operator<=>(Id, Id) noexcept = default;
private:
std::uint64_t value_;
};
// `struct CustomerTag` here both declares a new struct (in pay, never defined) and
// uses it as the tag, in one go. `using` gives the result a short name.
using CustomerId = Id<struct CustomerTag>;
using InvoiceId = Id<struct InvoiceTag>;
  • Id<CustomerTag> and Id<InvoiceTag> are different types, because their template arguments differ. Neither converts to the other, so passing an invoice id where a customer id is expected does not compile. That is B1.
  • The tag is only declared. struct CustomerTag inside the alias declares a struct named pay::CustomerTag and does nothing else. No object of it is ever created. A type parameter that only tells types apart is sometimes called a phantom type.
  • The constructor is explicit, so a plain number never becomes an id by accident. Making one is always visible in the code: CustomerId{42}.
  • There is no default constructor. An id always names something. If “no customer” is possible, say so with std::optional<CustomerId> rather than a magic CustomerId{0}.
  • The only operations are comparisons, from the defaulted operator<=>. Adding two ids, or multiplying one by two, means nothing, so it does not compile.
  • It costs nothing in space. An Id holds only its number; the example’s tests check with static_assert that it is the size of a std::uint64_t and trivially copyable, so copying one copies only the number.

One std::hash specialization makes every kind of id usable as a key in std::unordered_map, as the identity page explained for one id type:

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

ids.hpp
// One specialization makes every Id usable as an unordered_map key.
// std::unordered_map finds a key's bucket by calling std::hash<Key>. This
// tells the library what std::hash means for an Id of any Tag (a
// "partial specialization": one rule for a whole family of types).
template <typename Tag>
struct std::hash<pay::Id<Tag>> {
// Hashes an Id by hashing the number inside it. std::hash<std::uint64_t>{}
// makes a standard hasher for the number, and (...) calls it at once.
std::size_t operator()(pay::Id<Tag> id) const noexcept {
return std::hash<std::uint64_t>{}(id.value());
}
};

Money: only the operations that mean something

Section titled “Money: only the operations that mean something”

The money type from Entities, value objects, and services held cents in the library’s one currency and did not check for overflow. The billing service needs more: three currencies (R1), exact totals (R2), and mistakes that do not compile.

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

money.hpp
// An amount held exactly, as a whole number of the currency's minor unit.
//
// Contract for every operation:
// - Combining two amounts needs one currency; otherwise it throws
// CurrencyMismatch.
// - A result that does not fit in std::int64_t throws std::overflow_error.
// - Nothing converts to or from floating point.
class Money {
public:
// Every std::int64_t is a valid amount, including negative ones (a
// refund or a credit), so this has no precondition.
// A named factory instead of a public constructor: the name says the
// number is in minor units, so from_minor(499, Currency::eur) reads as
// "499 cents", EUR 4.99. `static` means it is called on the class,
// Money::from_minor(...), not on an existing Money.
[[nodiscard]] static constexpr Money from_minor(std::int64_t units, Currency currency) noexcept {
return Money(units, currency);
}
// Money::from_minor(4.99, Currency::eur) would otherwise compile and quietly
// become 4 cents. Deleting the floating-point form makes it an error.
// How: `template <std::floating_point F>` is a version of from_minor for
// any F that is float, double, or long double. For a double argument it
// is an exact match, so the compiler prefers it to converting the double
// to int64_t, and `= delete` turns picking it into a compile error. For
// an integer argument the constraint fails, so the version above is used.
template <std::floating_point F>
static Money from_minor(F units, Currency currency) = delete;
[[nodiscard]] constexpr std::int64_t minor_units() const noexcept { return units_; }
[[nodiscard]] constexpr Currency currency() const noexcept { return currency_; }
// Equal when the currency and the amount are both equal, so EUR 0 is
// not equal to USD 0.
// `= default` compares the members one by one (units_, then currency_),
// and never throws. != comes with it automatically.
friend bool operator==(Money, Money) noexcept = default;
private:
// Private, so code outside the class must go through from_minor.
constexpr Money(std::int64_t units, Currency currency) noexcept
: units_(units), currency_(currency) {}
std::int64_t units_;
Currency currency_;
};
// The arithmetic needs only the public interface, so it is not a friend.
// Each takes its Money by value (a Money is two small fields, cheap to
// copy) and returns a new Money. + and - throw CurrencyMismatch for two
// currencies; all four throw std::overflow_error if the result does not fit.
[[nodiscard]] Money operator+(Money left, Money right);
[[nodiscard]] Money operator-(Money left, Money right);
[[nodiscard]] Money operator*(Money amount, std::int64_t times);
[[nodiscard]] Money operator*(std::int64_t times, Money amount);
// Ordering two currencies has no answer, so this throws CurrencyMismatch.
// From this one function the compiler provides <, <=, > and >= for Money.
// std::strong_ordering is the result type of <=>: less, equal, or greater.
[[nodiscard]] std::strong_ordering operator<=>(Money left, Money right);
// Money * 1.5 would otherwise convert 1.5 to 1 without a word.
// The same trick as the deleted from_minor above, for both orders.
template <std::floating_point F>
Money operator*(Money amount, F times) = delete;
template <std::floating_point F>
Money operator*(F times, Money amount) = delete;

A Money holds a whole number of the currency’s minor unit: cents for euros and dollars, yen for yen, which has no smaller unit in use. Every amount the service handles is exact, adding two of them is exact, and the B4 rounding errors cannot happen (R2). The only place a fraction of a minor unit appears is in a discount, and that rounding is in one function, with its rule written down.

The factory’s name says the unit: Money::from_minor(499, Currency::eur) is EUR 4.99. A caller who has euros has to think about the conversion, which is the point. That is B2.

A double passed where a std::int64_t is expected is converted silently, dropping the fraction. When we compiled such a call by itself with -std=c++20 -Wall -Wextra -Wpedantic, GCC 11.4 gave no warning at all. Clang 14 warned for a literal such as 4.99, but neither compiler warned when the double was in a variable.

The deleted function template closes that gap. For an int or a std::int64_t argument, the template does not apply, because the std::floating_point constraint fails, and the ordinary function is called. For a double, the template is an exact match, which is better than a conversion, so overload resolution picks it, and calling a deleted function does not compile. The two deleted operator* templates after the class do the same for price * 1.5.

The deleted templates block floating point only. Other integer types still convert: price * true compiles, and so does price * items.size(), where a std::size_t too large for a std::int64_t becomes a wrong, possibly negative, count. Multiplying by a count type such as the Quantity below, instead of an integer, would close that gap too; the example keeps a plain integer to stay short.

operator+, operator-, operator*, and operator<=> need only minor_units() and currency(), which are public, so they are plain functions outside the class rather than friends. Each checks the currency, then checks that the result fits in a std::int64_t, and throws std::overflow_error instead of letting the number wrap. An int64_t holds about 9.2 × 10¹⁸ cents, over 90 thousand trillion euros, so overflow needs absurd amounts, but a wrapped total would be a silent and very wrong invoice, and the check is cheap.

The full set of operations is a design decision, so it is worth writing down:

Expression Allowed? Why
price + price, price - price yes, one currency the sum of two amounts is an amount; two currencies throw CurrencyMismatch (B6)
price * 3, 3 * price yes three of something that costs price
price * price no “euros squared” means nothing
price * 1.5 no, deleted would silently become price * 1
price + 5 no 5 what? Make the 5 a Money first
price / 3 no dividing loses a remainder; use allocate (below)
price == other yes equal when the currency and the amount are equal; never throws
price < other yes, one currency two currencies have no order, so it throws CurrencyMismatch

Dividing EUR 10.00 into three instalments cannot give three equal amounts in whole cents. 10.00 / 3 rounded is 3.33, and three of those are 9.99: a cent has disappeared. R4 asks for parts that add up to exactly the total, so Money has no division, and allocate does the job instead:

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

money.hpp
// Splits amount into `parts` amounts that add up to exactly amount and
// differ by at most one minor unit. The parts that take an extra unit
// come first, so EUR 10.00 in 3 parts is EUR 3.34, 3.33, 3.33, and
// EUR -10.00 is EUR -3.34, -3.33, -3.33.
// Throws std::invalid_argument if parts < 1. The parts are in the same
// currency as amount, and the vector has exactly `parts` elements.
[[nodiscard]] std::vector<Money> allocate(Money amount, int parts);

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

money.cpp
// The idea: give every part the same base amount, then hand out the units
// that division left over, one each, to the first parts. Example: 1000
// cents in 3 parts is a base of 333 with 1 left over, so 334, 333, 333.
std::vector<Money> allocate(Money amount, int parts) {
if (parts < 1) { // checked first: 0 would divide by zero below
throw std::invalid_argument("allocate: parts must be at least 1");
}
const std::int64_t units = amount.minor_units();
// parts (an int) is converted to std::int64_t for these two lines.
const std::int64_t base = units / parts; // rounds toward zero
// base * parts + left_over == units always holds, and left_over is
// smaller in size than parts: 1000 % 3 is 1, and -1000 % 3 is -1.
const std::int64_t left_over = units % parts; // same sign as units
// The extra unit is +1 for a positive amount and -1 for a negative one,
// so each extra moves its part away from zero, as the remainder did.
const std::int64_t step = left_over < 0 ? -1 : 1;
std::vector<Money> result;
result.reserve(static_cast<std::size_t>(parts)); // one allocation; parts >= 1
for (int i = 0; i < parts; ++i) {
// std::abs(left_over) is how many parts get an extra unit: the
// first ones, i = 0, 1, ..., up to that count minus one.
const bool takes_one_more = i < std::abs(left_over);
result.push_back(Money::from_minor(base + (takes_one_more ? step : 0), amount.currency()));
}
return result; // the parts add up to units exactly, in amount's currency
}
How this code works: allocate
  1. Refuse a bad count. parts < 1 throws before anything else, which also keeps the division below from dividing by zero.
  2. Divide. base is what every part gets, and left_over is what division could not share out. Together they rebuild the amount exactly: base * parts + left_over == units.
  3. Pick the direction. step is +1 for a positive remainder and -1 for a negative one. A remainder of zero also gives +1, but then no part uses it.
  4. Build the parts. The first std::abs(left_over) parts get base + step; the rest get base.

Three runs, with the values the tests and the demo use:

Call base left_over step Parts
1000 cents, 3 parts 333 1 +1 334, 333, 333
-1000 cents, 3 parts -333 -1 -1 -334, -333, -333
1419 cents (EUR 14.19), 4 parts 354 3 +1 355, 355, 355, 354

In each row the parts add up to the amount: 334 + 333 + 333 = 1000, and 355 × 3 + 354 = 1419. No part differs from another by more than one cent, because at most one extra unit is added to any part.

Integer division gives the base amount, and the remainder, which is smaller in size than parts, gives one extra minor unit to that many of the parts. Division in C++ rounds toward zero, and % then has the sign of the amount, so a negative amount, such as a refund, splits the same way with the extra units negative. Which parts get the extra units is a rule, here “the first ones”, and a requirement can change it; what cannot change is that the parts add up.

Some rules depend on the value, not the type: a quantity must be at least 1, and a discount must be between 0% and 100%. The compiler cannot check a number typed by a user. What a type can do is check the rule once, when the value is made, and refuse to exist otherwise.

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

invoice.hpp
// A number of items: at least 1. The check runs once, in the constructor,
// so every function that takes a Quantity can rely on it without checking.
class Quantity {
public:
// Throws std::invalid_argument if count < 1.
// `explicit`: an int never turns into a Quantity silently, so a function
// that takes a Quantity cannot be handed a bare number by mistake.
explicit Quantity(int count);
[[nodiscard]] int count() const noexcept { return count_; }
friend bool operator==(Quantity, Quantity) noexcept = default;
private:
int count_; // set once in the constructor; no setter, so it stays >= 1
};

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

invoice.hpp
// A discount from 0% to 100%, held in basis points (hundredths of a
// percent) so that 12.5% is exact.
// The only ways to make one are the two static factories below, whose
// names say what the number means; the constructor is private.
class Discount {
public:
// 0 basis points: no discount at all.
[[nodiscard]] static Discount none() noexcept { return Discount(0); }
// Throws std::invalid_argument unless 0 <= points <= 10000.
// basis_points(1250) is 12.5%, and 10000 is 100%.
[[nodiscard]] static Discount basis_points(int points);
[[nodiscard]] int in_basis_points() const noexcept { return points_; }
// The amount after the discount. The discount itself is rounded to the
// nearest minor unit, with halves rounded away from zero, so EUR 0.05
// at 50% is EUR 0.02 (a discount of EUR 0.03). Cannot overflow.
[[nodiscard]] Money apply_to(Money amount) const;
friend bool operator==(Discount, Discount) noexcept = default;
private:
// Does not check: only none() and basis_points(), which have already
// checked the number, may call it.
explicit Discount(int points) noexcept : points_(points) {}
int points_;
};
  • Every Quantity that exists is at least 1. The constructor throws otherwise, and the class has no setter, so nothing can change it later. A function that takes a Quantity does not need to check again, and does not need a test for the zero case.
  • The check runs where the data enters. The order screen turns the text the user typed into a Quantity once. If it is 0, the user gets the message there (R5), and nothing further into the program ever sees an invalid count.
  • Discount uses a named factory, Discount::basis_points(1250), because a constructor called with 1250 would not say what the number means. One basis point is a hundredth of a percent, so 12.5% is exactly 1250 (R3). A Discount::percent(int) factory could be added for whole percentages.
  • Being a different type also stops B3. Quantity and Discount are no longer both int, so they cannot be passed in each other’s place.

The rounding rule is part of the discount’s contract, written in its comment and implemented in one place:

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

invoice.cpp
// Works out the discount, `off`, in minor units, rounded to the nearest
// unit with halves away from zero, then subtracts it from the amount.
// The exact discount is units * points_ / 10000.
Money Discount::apply_to(Money amount) const {
// amount * points / 10000 could overflow, so split amount into a part
// that divides exactly and a remainder below 10000.
// units == whole * 10000 + rest, so the exact discount is
// whole * points_ (exact, no fraction) plus rest * points_ / 10000.
const std::int64_t units = amount.minor_units();
const std::int64_t whole = units / 10'000;
const std::int64_t rest = units % 10'000; // same sign as units
// Integer division drops the fraction (rounds toward zero). Adding half
// of 10000 first, with the sign of rest, makes it round to the nearest
// instead: 2.5 becomes 3, and -2.5 becomes -3.
const std::int64_t half = rest < 0 ? -5'000 : 5'000;
// rest * points_ is at most 9999 * 10000 in size, far from overflowing.
// Example, EUR 16.22 at 12.5%: whole 0, rest 1622, and
// (1622 * 1250 + 5000) / 10000 = 2032500 / 10000 = 203, so off is 203.
const std::int64_t off = whole * points_ + (rest * points_ + half) / 10'000;
// off always lies between 0 and units (it equals units at 100%), so
// this subtraction stays in range: 1622 - 203 = 1419, EUR 14.19.
return amount - Money::from_minor(off, amount.currency());
}
How this code works: Discount::apply_to

The exact discount is units * points_ / 10000, but units * points_ can be far too large for a std::int64_t. So the amount is split first:

  1. Split. whole = units / 10000 and rest = units % 10000, so units == whole * 10000 + rest, and rest is less than 10000 in size.
  2. The whole part is exact. whole * 10000 * points_ / 10000 is just whole * points_: no division, so no rounding, and it fits because whole is at most a ten-thousandth of the amount.
  3. The rest is rounded. rest * points_ is at most 9999 × 10000, small enough for any std::int64_t. Adding half (5000, or -5000 for a negative rest) before dividing by 10000 turns “drop the fraction” into “round to the nearest, halves away from zero”.
  4. Subtract. The price after the discount is the amount minus off.

Worked through with real values:

Amount Discount whole rest half off Result
EUR 16.22 12.5% 0 1622 5000 (2027500 + 5000) / 10000 = 203 EUR 14.19
EUR 0.05 50% 0 5 5000 (25000 + 5000) / 10000 = 3 EUR 0.02
EUR -0.05 50% 0 -5 -5000 (-25000 - 5000) / 10000 = -3 EUR -0.02

The second row is the half case: 2.5 cents of discount rounds to 3. Without half, 25000 / 10000 would be 2: integer division just drops the fraction, which rounds toward zero.

units * points could overflow for a large amount, so the code splits the amount into whole multiples of 10000 minor units, which divide exactly, and a remainder, which is small. Adding half of 10000, with the remainder’s sign, before the last division rounds halves away from zero. The tests check a value that rounds, a negative amount, and the largest amount at 100%.

A type carries some rules. The rest belong in the function’s contract: what the caller must make true before the call (the preconditions), what the function makes true after it (the postconditions), what it throws, and what state it leaves behind if it does. The invoice writes its contract next to each function:

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

invoice.hpp
// One invoice: who it is for, its currency, its lines, and a running
// subtotal. It owns its lines by value, in a vector.
// Invariant: subtotal_ always equals the sum of quantity * unit_price over
// lines_, and every line is in currency_. add_line is the only function
// that changes either, and it keeps the two in step.
class Invoice {
public:
// The id types differ, so passing the customer first does not compile.
Invoice(InvoiceId id, CustomerId customer, Currency currency);
[[nodiscard]] InvoiceId id() const noexcept { return id_; }
[[nodiscard]] CustomerId customer() const noexcept { return customer_; }
[[nodiscard]] Currency currency() const noexcept { return currency_; }
[[nodiscard]] const std::vector<Line>& lines() const noexcept { return lines_; }
// Throws CurrencyMismatch if unit_price is not in the invoice's
// currency, and std::overflow_error if a total would not fit. If it
// throws, the invoice is unchanged (the strong guarantee).
// description is taken by value and moved into the new line, so a
// caller passing a temporary string pays for no copy.
void add_line(std::string description, Quantity quantity, Money unit_price);
[[nodiscard]] Money subtotal() const noexcept { return subtotal_; }
// The subtotal after the discount. Not noexcept: apply_to uses Money's
// subtraction, which is allowed to throw, although for a valid discount
// it never does. The invoice itself is not changed (const).
[[nodiscard]] Money total(Discount discount) const { return discount.apply_to(subtotal_); }
private:
InvoiceId id_;
CustomerId customer_;
Currency currency_;
std::vector<Line> lines_;
Money subtotal_; // always the sum of the lines
};

add_line promises the strong guarantee from Exception safety and failure atomicity: if it throws, the invoice is as it was (R5). The implementation computes everything that can throw before changing anything. The one change that can still throw, push_back, has the strong guarantee itself, because Line’s move constructor does not throw; the last step, assigning a Money, cannot throw:

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

invoice.cpp
void Invoice::add_line(std::string description, Quantity quantity, Money unit_price) {
// Compute everything that can throw before changing anything. push_back
// has the strong guarantee itself; assigning a Money cannot throw.
// Step 1, nothing changed yet: may throw std::overflow_error.
const Money line_total = unit_price * quantity.count();
// Still nothing changed. + checks the currencies, so a price in another
// currency than the invoice's throws here, before the line is stored.
const Money new_subtotal = subtotal_ + line_total; // CurrencyMismatch, overflow
// Step 2, the first change. If push_back throws (out of memory), the
// vector is left as it was. std::move hands the string to the Line.
lines_.push_back(Line{std::move(description), quantity, unit_price});
// Step 3: cannot throw, so the line and the subtotal change together.
subtotal_ = new_subtotal;
}

Notice how much of the contract the types now carry. The comment does not need to say “quantity must be at least 1”, or “unit_price is in cents”, or “the first argument is the invoice”; those are in the parameter types and cannot be broken. What is left is the rule that needs two values together, “the price is in the invoice’s currency”, and that is checked on every call.

A function with a wide contract accepts every value of its parameter types and does something defined with each, perhaps throwing. Money::from_minor has a wide contract: every std::int64_t is a valid amount. allocate has one too: it throws std::invalid_argument for parts < 1 instead of requiring the caller never to pass it.

A function with a narrow contract has a precondition that the caller must keep, and does not promise what happens if it is broken. std::vector::operator[] is the standard example: an index out of range is undefined behavior. A narrow contract is not a bad design; it says “checking is the caller’s job”, which is right when the caller already knows, and checking again on every call would cost time in an inner loop. It is often checked in debug builds only:

// Precondition: i < lines().size(). Not checked in release builds.
// assert (from <cassert>) stops the program with a message if its condition
// is false, but only in builds without NDEBUG defined, usually debug
// builds. In a release build the line disappears, and a bad i makes
// lines_[i] undefined behavior: that is what "narrow" means.
const Line& line(std::size_t i) const noexcept {
assert(i < lines_.size());
return lines_[i]; // a reference into the vector: add_line may invalidate it
}

This code is illustrative and was not compiled.

A strong type turns a narrow contract into a wide one for free: a function taking Quantity has no “count must be at least 1” precondition left, because every Quantity already meets it.

Each rule can be enforced in one of four places, from strongest to weakest:

Where When it is checked Example here Use it when
In the type: the wrong thing does not compile compile time, always CustomerId vs InvoiceId; no price * price the rule is about kinds of value, not their numbers
In a constructor or factory once, when the value is made Quantity, Discount the rule is about one value, and many functions need it
In the function, on every call every call the currency check in add_line the rule needs several values together
In the documentation, maybe an assert debug builds, or never a narrow line(i) checking is too costly, and the caller already knows

Move a rule up the table when you can. A rule in a type cannot be forgotten by a new caller; a rule in a comment can. API contracts and validation placement asks the same question for a whole application, deciding which layer checks what; this table is the same idea inside one C++ API.

B7 is the same problem as B1 in a smaller form: true says nothing at the call. A two-valued enum class names the choice:

// Before: what do true and false mean?
send_invoice(invoice, true, false);
// After: the call says what it does.
enum class Delivery { email, post };
enum class Copy { none, to_accountant };
send_invoice(invoice, Delivery::email, Copy::none);

This code is illustrative and was not compiled.

Two enum class types are also different types from each other and from bool, so they cannot be swapped. For round_up the better fix was to remove the parameter: R3 fixes one rounding rule, and the discount type applies it.

A test that runs cannot check that some code fails to compile. A static_assert can check it in a roundabout way: a concept with a requires expression is true if an expression would compile and false if it would not, without compiling a broken program.

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

compile_checks.cpp
// A concept is a named yes-or-no question about types, answered by the
// compiler. `requires(A a, B b) { a + b; }` means "given an A named a and
// a B named b, would the expression a + b compile?". Nothing is run; the
// compiler only checks the expression. So addable<Money, Money> is true,
// and addable<Money, std::int64_t> is false.
template <typename A, typename B>
concept addable = requires(A a, B b) { a + b; };
template <typename A, typename B>
concept multipliable = requires(A a, B b) { a * b; };
// True if Money::from_minor accepts a T. A call that would pick a deleted
// function counts as not compiling, so makes_money<double> is false.
template <typename T>
concept makes_money = requires(T units) { Money::from_minor(units, Currency::eur); };
// static_assert(condition) stops the build with an error if the condition
// is false. The std::is_..._v traits from <type_traits> answer questions
// such as "can a CustomerId be made from these arguments?" at compile time.
// Ids: no silent conversion from a number, and no mixing of kinds.
// is_convertible asks about implicit conversion only (what `explicit`
// forbids); is_constructible asks whether any constructor accepts the
// arguments, explicit or not.
static_assert(!std::is_convertible_v<std::uint64_t, CustomerId>);
static_assert(!std::is_constructible_v<InvoiceId, CustomerId>);
static_assert(!std::is_default_constructible_v<CustomerId>);
static_assert(!addable<CustomerId, CustomerId>);
static_assert(sizeof(CustomerId) == sizeof(std::uint64_t)); // no space cost
static_assert(std::is_trivially_copyable_v<CustomerId>);
// The swapped call from the old API no longer compiles.
static_assert(std::is_constructible_v<pay::Invoice, InvoiceId, CustomerId, Currency>);
static_assert(!std::is_constructible_v<pay::Invoice, CustomerId, InvoiceId, Currency>);
// Money: only the operations that mean something.
static_assert(addable<Money, Money>);
static_assert(!addable<Money, std::int64_t>);
static_assert(multipliable<Money, std::int64_t>);
static_assert(multipliable<int, Money>);
static_assert(!multipliable<Money, Money>);
static_assert(!multipliable<Money, double>);
static_assert(makes_money<std::int64_t>);
static_assert(makes_money<int>);
static_assert(!makes_money<double>);
// Money's constructor is private, so from outside the class it does not
// count: only from_minor can make a Money.
static_assert(!std::is_constructible_v<Money, std::int64_t, Currency>); // only via from_minor
// Rules checked at run time still need their types: no Quantity from text.
static_assert(!std::is_convertible_v<int, pay::Quantity>);
static_assert(!std::is_constructible_v<pay::Quantity, std::string>);
  • addable<Money, Money> is true and addable<Money, std::int64_t> is false. Writing the positive cases too matters: a concept that is written wrongly, for example with a misspelled member name, is false for everything, and a test of only negative cases would then pass for the wrong reason.
  • std::is_constructible_v<pay::Invoice, CustomerId, InvoiceId, Currency> being false is the B1 call, written as a test.
  • A deleted function counts as “does not compile”, so makes_money<double> is false.
  • These are checked by the compiler when the file is built. If someone adds an implicit conversion to Id next year, the build fails with the line that says why.

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

main.cpp
int main() {
// `using pay::Money;` lets this function write Money for pay::Money.
using pay::Currency;
using pay::Money;
using pay::Quantity;
// Each argument says what it is: swapping the two ids would not compile.
pay::Invoice invoice(pay::InvoiceId{7}, pay::CustomerId{42}, Currency::eur);
// 3 notebooks at 499 cents (EUR 4.99) each, then one pen at EUR 1.25.
invoice.add_line("Notebook", Quantity{3}, Money::from_minor(499, Currency::eur));
invoice.add_line("Pen", Quantity{1}, Money::from_minor(125, Currency::eur));
std::cout << "Invoice " << invoice.id().value() << " for customer "
<< invoice.customer().value() << '\n';
// A range-for over the invoice's vector of lines; each Line is looked at
// through a const reference, so nothing is copied or changed.
for (const pay::Line& line : invoice.lines()) {
std::cout << " " << line.quantity.count() << " x " << line.description << " at "
<< to_string(line.unit_price) << '\n';
}
// 1250 basis points is 12.5%. The ' in 1'250 is only a digit separator.
const auto discount = pay::Discount::basis_points(1'250);
const Money total = invoice.total(discount);
std::cout << "Subtotal " << to_string(invoice.subtotal()) << ", " << to_string(discount)
<< " off, total " << to_string(total) << '\n';
std::cout << "In 4 instalments:";
// allocate returns a temporary vector; the range-for keeps it alive
// until the loop ends. Each Money is small, so it is copied by value.
for (const Money part : pay::allocate(total, 4)) {
std::cout << ' ' << to_string(part);
}
std::cout << '\n';
// Mistakes in data are caught when a value is made or combined.
// A yen price: add_line's + finds the two currencies and throws
// CurrencyMismatch, and the invoice is left unchanged.
try {
invoice.add_line("Tea", Quantity{2}, Money::from_minor(300, Currency::jpy));
} catch (const pay::CurrencyMismatch& error) {
std::cout << "Rejected: " << error.what() << '\n';
}
// Quantity{0} throws std::invalid_argument while the arguments are being
// made, so add_line is never even called.
try {
invoice.add_line("Ink", Quantity{0}, Money::from_minor(899, Currency::eur));
} catch (const std::invalid_argument& error) {
std::cout << "Rejected: " << error.what() << '\n';
}
std::cout << "Still " << invoice.lines().size() << " lines, subtotal "
<< to_string(invoice.subtotal()) << '\n';
}
Expected output
Invoice 7 for customer 42
3 x Notebook at EUR 4.99
1 x Pen at EUR 1.25
Subtotal EUR 16.22, 12.5% off, total EUR 14.19
In 4 instalments: EUR 3.55 EUR 3.55 EUR 3.55 EUR 3.54
Rejected: currency mismatch: EUR and JPY
Rejected: quantity must be at least 1, got 0
Still 2 lines, subtotal EUR 16.22

Reading the output:

  • The subtotal is 3 × 4.99 + 1.25 = 16.22, exact.
  • 12.5% of EUR 16.22 is EUR 2.0275, rounded to EUR 2.03 off, so the total is EUR 14.19.
  • EUR 14.19 in four parts is 3.55, 3.55, 3.55, and 3.54: the three left over cents go to the first three parts, and the parts add up to 14.19.
  • The yen price and the zero quantity are rejected with messages, and the invoice still has its two lines.

The run-time rules are tested like any other behavior:

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

test_money.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false, LLD_CHECK_EQ(actual, expected) records one and
// prints both values if they differ, and LLD_CHECK_THROWS(expression, type)
// fails unless the expression throws that type of exception. They come
// from the site's small test header, lld_test.hpp. eur(cents), defined
// above these tests, is short for Money::from_minor(cents, Currency::eur).
// Plain arithmetic, including a negative result and the ordering.
LLD_TEST(amounts_in_one_currency_add_and_subtract_exactly) {
LLD_CHECK(eur(499) + eur(125) == eur(624));
LLD_CHECK(eur(100) - eur(250) == eur(-150));
LLD_CHECK(eur(499) * 3 == eur(1'497));
LLD_CHECK(eur(100) < eur(250));
}
// Each mixed-currency operation throws, except ==, which answers false.
LLD_TEST(two_currencies_do_not_combine_or_compare) {
const Money yen = Money::from_minor(300, Currency::jpy);
LLD_CHECK_THROWS(eur(100) + yen, pay::CurrencyMismatch);
LLD_CHECK_THROWS(eur(100) - yen, pay::CurrencyMismatch);
LLD_CHECK_THROWS(eur(100) < yen, pay::CurrencyMismatch);
LLD_CHECK(!(eur(0) == Money::from_minor(0, Currency::usd))); // == never throws
}
// The edges of std::int64_t: one step past the largest or the smallest
// value throws. The last two checks are results right at the edge, which
// must still work: min - min is 0, and (max / 2) * 2 is max - 1, because
// max is odd.
LLD_TEST(results_that_do_not_fit_throw_instead_of_wrapping) {
using Limits = std::numeric_limits<std::int64_t>;
LLD_CHECK_THROWS(eur(Limits::max()) + eur(1), std::overflow_error);
LLD_CHECK_THROWS(eur(Limits::min()) - eur(1), std::overflow_error);
LLD_CHECK_THROWS(eur(Limits::max() / 2 + 1) * 2, std::overflow_error);
// -min does not fit: min is -9223372036854775808, max only ...807.
LLD_CHECK_THROWS(eur(Limits::min()) * -1, std::overflow_error);
LLD_CHECK(eur(Limits::min()) - eur(Limits::min()) == eur(0));
LLD_CHECK(eur(Limits::max() / 2) * 2 == eur(Limits::max() - 1));
}
// One exact example, then the three promises of allocate checked for 6
// amounts and 1 to 7 parts each (42 splits): the right number of parts,
// a sum equal to the amount, and parts that differ by at most one unit.
LLD_TEST(allocate_keeps_every_cent) {
const std::vector<Money> parts = pay::allocate(eur(1'000), 3);
// The extra brackets keep the commas in the braces from being read as
// separate macro arguments.
LLD_CHECK(parts == (std::vector<Money>{eur(334), eur(333), eur(333)}));
for (const std::int64_t cents : {0, 1, 7, 1'000, -1'000, 99'999}) {
for (int count = 1; count <= 7; ++count) {
const std::vector<Money> split = pay::allocate(eur(cents), count);
LLD_CHECK_EQ(split.size(), static_cast<std::size_t>(count));
// std::accumulate adds every part to a starting value of eur(0),
// using Money's own +.
LLD_CHECK(std::accumulate(split.begin(), split.end(), eur(0)) == eur(cents));
// The extra units go to the first parts, so the first and the last
// part are the largest and the smallest (or the other way round,
// for a negative amount). Checking both directions covers both.
LLD_CHECK(split.front().minor_units() - split.back().minor_units() <= 1);
LLD_CHECK(split.back().minor_units() - split.front().minor_units() <= 1);
}
}
LLD_CHECK_THROWS(pay::allocate(eur(100), 0), std::invalid_argument);
}

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

test_invoice.cpp
// The same test macros as in test_money.cpp, and the same eur(cents)
// helper, defined above these tests.
// Quantity{0} and Quantity{-3} throw from the constructor: such a Quantity
// never exists. 1, the smallest valid count, is accepted.
LLD_TEST(a_quantity_is_at_least_one) {
LLD_CHECK_EQ(Quantity{1}.count(), 1);
LLD_CHECK_THROWS(Quantity{0}, std::invalid_argument);
LLD_CHECK_THROWS(Quantity{-3}, std::invalid_argument);
}
// Just outside each end of 0 to 10000 is refused; each end itself is
// accepted, and 100% off leaves nothing to pay.
LLD_TEST(a_discount_is_between_none_and_all) {
LLD_CHECK_THROWS(Discount::basis_points(-1), std::invalid_argument);
LLD_CHECK_THROWS(Discount::basis_points(10'001), std::invalid_argument);
LLD_CHECK(Discount::basis_points(0) == Discount::none());
LLD_CHECK(Discount::basis_points(10'000).apply_to(eur(1'999)) == eur(0));
}
// At 50%, EUR 0.05 gives an exact discount of 2.5 cents: it rounds to 3,
// leaving 2. The 12.5% case is the demo's invoice. The last check uses the
// largest amount there is, which would overflow if apply_to multiplied
// the whole amount by the basis points.
LLD_TEST(a_discount_rounds_half_away_from_zero) {
const Discount half = Discount::basis_points(5'000);
LLD_CHECK(half.apply_to(eur(5)) == eur(2)); // 2.5 off rounds to 3
LLD_CHECK(half.apply_to(eur(-5)) == eur(-2)); // a credit rounds the same way
LLD_CHECK(Discount::basis_points(1'250).apply_to(eur(1'622)) == eur(1'419));
const Money most = eur(std::numeric_limits<std::int64_t>::max());
LLD_CHECK(Discount::basis_points(10'000).apply_to(most) == eur(0)); // no overflow
}

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

test_invoice.cpp
// empty_invoice(), defined above these tests, returns a new euro invoice
// with no lines.
// 3 * 499 + 125 = 1622, and no discount leaves the total the same.
LLD_TEST(an_invoice_adds_up_its_lines) {
pay::Invoice invoice = empty_invoice();
invoice.add_line("Notebook", Quantity{3}, eur(499));
invoice.add_line("Pen", Quantity{1}, eur(125));
LLD_CHECK(invoice.subtotal() == eur(1'622));
LLD_CHECK(invoice.total(Discount::none()) == eur(1'622));
}
// The strong guarantee, checked: after one good line, two calls that throw
// (a yen price, and a total too large for std::int64_t) leave exactly the
// one line and its subtotal of 1497.
LLD_TEST(a_rejected_line_leaves_the_invoice_unchanged) {
pay::Invoice invoice = empty_invoice();
invoice.add_line("Notebook", Quantity{3}, eur(499));
LLD_CHECK_THROWS(invoice.add_line("Tea", Quantity{2}, Money::from_minor(300, Currency::jpy)),
pay::CurrencyMismatch);
// 2 * max does not fit, so the multiplication in add_line throws.
const Money most = eur(std::numeric_limits<std::int64_t>::max());
LLD_CHECK_THROWS(invoice.add_line("Gold", Quantity{2}, most), std::overflow_error);
LLD_CHECK_EQ(invoice.lines().size(), std::size_t{1});
LLD_CHECK(invoice.subtotal() == eur(1'497));
}
  • The overflow tests use the limits of std::int64_t, including the case that only just fits, so the checks are not off by one.
  • The allocate test checks the properties for many amounts and part counts, not one hand-worked answer: the right number of parts, a sum equal to the amount, and parts that differ by at most one unit. Property-based and table-driven tests takes that idea further, with a split of a bill into cents.
  • The rule tests check each boundary on both sides: 0 and 1 for a quantity, -1, 0, 10000, and 10001 for a discount.
  • The invoice test checks R5’s second half: after a rejected line, the invoice is unchanged.
  • There is no test that the B1 call is caught at run time, because it cannot happen at run time. The compile checks hold that rule.

class pay::Id

template on Tag; CustomerId and InvoiceId are aliases

Data members

  • std::uint64_t value_;

Member functions

  • explicit Id(std::uint64_t value) noexcept;
  • std::uint64_t value() const noexcept;
  • friend auto operator<=>(Id, Id) = default; comparisons only

class pay::Money

whole minor units in one currency; immutable

Data members

  • std::int64_t units_;
  • Currency currency_;

Member functions

  • static Money from_minor(std::int64_t units, Currency currency) noexcept;
  • static Money from_minor(F units, Currency currency) = delete; F floating point
  • std::int64_t minor_units() const noexcept;
  • Currency currency() const noexcept;
  • friend bool operator==(Money, Money) = default;

class pay::Quantity

invariant: count is at least 1

Data members

  • int count_;

Member functions

  • explicit Quantity(int count); throws std::invalid_argument
  • int count() const noexcept;

class pay::Discount

invariant: 0 to 10000 basis points

Data members

  • int points_;

Member functions

  • static Discount basis_points(int points); throws std::invalid_argument
  • Money apply_to(Money amount) const; rounds half away from zero

class pay::Invoice

invariant: subtotal is the sum of the lines

Data members

  • std::vector<Line> lines_;
  • Money subtotal_;

Member functions

  • Invoice(InvoiceId id, CustomerId customer, Currency currency);
  • void add_line(std::string description, Quantity quantity, Money unit_price); strong
  • Money subtotal() const noexcept;
  • Money total(Discount discount) const;
The strong types in the invoice example; members summarized

The arithmetic on Money (+, -, *, <=>), allocate, and the to_string functions are non-member functions in namespace pay.

When strong types fit, and when they do not

Section titled “When strong types fit, and when they do not”

Strong types fit when:

  • Several values share a representation but not a meaning: ids of different kinds, amounts in different currencies or units, a count and a percentage. These are where swaps happen.
  • A value has rules that many functions rely on, such as a range or a format. Checking once beats checking everywhere.
  • The value crosses an API that other people or other teams call. The type is documentation the compiler reads.
  • A mistake is expensive: money, medical doses, physical units.

They are not worth it when:

  • The value never leaves one function, such as a loop index or a temporary count. A wrapper adds typing and protects nothing.
  • There is only one value of that kind in a signature and no rule on it. A std::string name beside no other string gains little from a Name type.
  • Every use unwraps it. If most code calls .value() to do arithmetic, the type has the wrong operations, or the value is not really a separate kind.

The real cost is at the edges: reading from a database or JSON, and writing back, needs a conversion for each type. Keep those conversions in the code that maps outside data to domain objects, so the rest of the program sees only the strong types. DTOs, domain objects, and persistence records shows where that mapping sits.

  • An implicit conversion back to the plain type. operator std::uint64_t() const on Id lets customer + 1 and invoice == customer compile again, through the conversion. Use a named value().
  • A default constructor that makes “no id”. CustomerId{} with a value of 0 becomes a magic value that every function has to check for. Use std::optional<CustomerId>.
  • Every operator “for completeness”. Adding operator+ to Id because it was easy makes invoice + invoice mean something. Add an operation only when a requirement needs it.
  • double for money, even inside a strong type. Wrapping a double in Money fixes B6 but not B4.
  • Checking the rule in every function instead of in the type. Each check is a place to get the boundary wrong, and a new function can forget it.
  • Reusing one tag for two aliases, which makes them one type (see the warning above).
  • Strong types inside, plain values in the API. If the public function still takes two std::uint64_ts and wraps them inside, the swap happens at the call, before the wrapping.
  • A currency with three minor digits, such as the Bahraini dinar. Add it to Currency, and a case to code and to minor_digits. Nothing else changes, because no code assumes two digits. The switch statements have no default, so the compiler warns about any one that is missed.
  • Converting between currencies. A conversion needs a rate and a rounding rule, so it becomes a type of its own, such as an ExchangeRate with a function that turns EUR into JPY. Money * Money still means nothing.
  • Ids become text, such as UUIDs from another system. Give Id a second template parameter for the representation, or write a separate template for text ids. Code that only passes ids around does not change; code that makes them from numbers does, and the compiler lists every place.
  • A fixed-amount discount as well as a percentage. That is a second kind of discount with a different rule and a different rounding, so it is a second type, and total takes either one (for example, as a std::variant) or there are two functions. Do not add an is_percentage flag to Discount.
  • Quantities by weight, such as 1.25 kg of tea. That is not a Quantity with a fraction; it is a different kind of value with its own unit (grams, as a whole number) and its own price per unit.

Exercise: Eliminate a parameter-swap bug

A customer can move credit from their account to another customer’s, for example to pay an invoice for a colleague. The service has this function:

// Moves cents of credit from one customer to another, to pay `invoice`.
void move_credit(std::uint64_t from_customer, std::uint64_t to_customer,
std::uint64_t invoice, std::int64_t cents);
// Compiles, but wrong: the invoice id comes first, which pushes the two
// customer ids one place to the right. All three are std::uint64_t, so
// the compiler cannot tell them apart.
move_credit(invoice_id, payer_id, payee_id, 500);

This code is illustrative and was not compiled.

The call has the invoice in the first place. Using the example’s pay types:

  1. Change the signature so that the call above does not compile.
  2. Which swap does your new signature still allow? Why can’t another strong type alone fix it without making the code worse?
  3. Fix that swap too, so that the call says which customer is which.
Show the explained answer

1. Use the strong types:

// Each id now has its own type, and the amount carries its currency.
void move_credit(pay::CustomerId from, pay::CustomerId to,
pay::InvoiceId invoice, pay::Money amount);

This declaration was compiled against the example with GCC 11.4 and Clang 14. Now the invoice id cannot go in a customer’s place, and the amount must be a Money in a stated currency, not a bare number of cents.

2. from and to are both CustomerId, so move_credit(payee, payer, invoice, amount) still compiles and moves the money the wrong way. Making PayerId and PayeeId separate types would stop it, but the same customer is a payer in one call and a payee in the next, so the code would convert between them all the time, and each conversion is another place for the same mistake. The difference between from and to is a role in this one call, not a kind of value.

3. Name the roles at the call. One way is a parameter struct with designated initializers:

// One struct holds all four arguments, so each can be named at the call.
struct CreditMove {
pay::CustomerId from;
pay::CustomerId to;
pay::InvoiceId invoice;
pay::Money amount;
};
void move_credit(const CreditMove& move);
// `{.from = payer, ...}` builds a CreditMove in place, setting each field
// by name (C++20 designated initializers), and passes it to move_credit.
move_credit({.from = payer, .to = payee, .invoice = pay::InvoiceId{7},
.amount = pay::Money::from_minor(500, pay::Currency::eur)});

We compiled this against the example with GCC 11.4 and Clang 14. What it does and does not catch:

  • Every argument is named at the call, so .from = payee is visible to a reviewer.
  • Leaving out a field does not compile, because CustomerId, InvoiceId, and Money have no default constructor.
  • C++20 requires designators in the order the fields are declared. Writing .to before .from was an error with GCC 11.4 and a warning with Clang 14 (-Wreorder-init-list), which this site’s -Werror builds turn into an error. That catches a reordered call, not a wrong one.
  • {.from = payee, .to = payer, ...} still compiles. The names make the mistake readable; they do not make it impossible.

Another way is to make the role part of the function: a member function on the payer’s account, payer_account.move_credit_to(payee, invoice, amount), where only one customer is a parameter. Both fixes work by leaving no two same-type values side by side.

  • Many bugs are wrong calls, not wrong functions: correct values in the wrong place. Plain ints and doubles let the compiler accept them.
  • A strong type gives a plain value a meaning of its own. Different meanings get different types, and a swap stops compiling.
  • One class template with a tag covers every kind of id. It is as small as the number it holds.
  • Give a type only the operations that mean something, and delete the conversions that would quietly lose data, such as from double.
  • Hold money as a whole number of minor units with its currency, and split it with an allocation that keeps every unit.
  • Check a rule about a value once, in its constructor or factory, where the data enters the program. Every function that receives the type can rely on it.
  • Write the contract next to each function, and enforce each rule as high up the table as it will go: type, constructor, function, comment.
  • Test that misuse does not compile with concepts and static_assert, and include the positive cases.