22
Type erasure and PImpl
A value-semantic AnyRateQuoter that erases unrelated concrete quoters, and a PImpl ledger that is a true compilation firewall.
Two idioms that both hide a type behind a stable surface:
- Type erasure.
AnyRateQuoterwraps any type satisfying aQuotableconcept behind a private hand-writtenConcept/Modelpair (unique_ptr<Concept>+clone()for deep copies). Four unrelated concrete quoters share no base class; aSurgeQuoterwith a per-call counter proves a copy is independent, and anInsuredQuoterwraps anotherAnyRateQuoter(erasure composed, the ch16 Decorator tie without inheritance). - PImpl.
RateQuoteLedgerkeeps its implementation behind aunique_ptr<Impl>so the header exposes nothing: adding fields toImplnever changessizeof(RateQuoteLedger)or forces consumers to recompile. Goes deeper than ch15 on ABI stability and theunique_ptrconst-propagation gotcha.
A C++23 try_record() returning std::expected is guarded for C++20.
Build, run, observe
./scripts/build.sh cpp23
./scripts/verify.sh cpp23 # 12/12 tests pass
./examples/22-type-erasure-pimpl/demo.sh cpp23
The demo stores four unrelated quoters in one vector, copies a stateful quoter
to show independence, composes an insured wrapper, and records quotes through the
PImpl ledger. Chapter 22 covers when to reach for each idiom. Builds
standalone and under the cpp20 preset (10 tests).