Posts

Type Erasure in C++

Image
One Box, Any Type: Understanding Type Erasure in C++ Or: How std::function stores a lambda, a function pointer, and a functor in the same box C++ rewards precise thinking about types. Most of the time, that precision is a feature. But occasionally the type system and the design pull in opposite directions, and the compiler rejects code that is, by every conceptual measure, reasonable. Consider a transaction monitor for a SystemC simulation. Every time a TLM transaction arrives, four separate objects need to respond: a Logger records it, a LatencyTracker measures it, a ProtocolChecker validates it, a CoverageCollector bins it. They share no base class, and they shouldn't need one. What they have in common is purely behavioral: they all respond to a transaction. So the obvious thing gets written: std :: vector < TransactionHandler > handlers ; handlers . push_back ( Logger {}); handlers . push_back ( LatencyTracker {}); handlers . push_back ( Pr...

Logarithms

Image
The Number That Barely Moves: CodePuz Mathematics · Algorithms · Intuition Most of What We Studied in School Stayed There Logarithms didn’t. They followed us into every codebase, quietly running inside the algorithms we rely on the most. There is a long list of things we studied in school mathematics and never encountered again. Trigonometric identities are near the top. Sin²θ + cos²θ = 1, the double angle formulae, pages of them, dutifully memorised and carefully reproduced in an exam, then quietly never thought about again. They had the decency to stay in school where we left them. Logarithms sat in the same chapter. Same compact notation, same air of abstraction, same unspoken question: when will I ever use this? So they got filed under the same heading: learned it, passed it, moved on. That turns out to be a significant mistake. Unlike most of what we memorised, logarithms never went away. They just went underground. There is one inside every binary searc...