Article

Reducing C++ template bloat by factoring out the type-dependent portions of the function

The Old New Thing ·The Old New Thing ·Published 2026-08-20 ·5 min read

This article discusses the cost of C++ template expansions and how to mitigate template bloat by using helper objects to encapsulate common functionality. It provides insights into optimizing template functions that accept lambdas.

From the article

C++ templates let you reuse code, but it comes at a cost: Each template expansion results in a different function. This is not a big deal for small functions, but the less trivial your function becomes, the larger the cost of the repeated expansions.

This is particularly expensive for functions that accept lambdas because every lambda is a unique type, so each time you invoke the template function with a lambda you get a different template expansion.

Sometimes I see large template functions that have very few type dependencies.


Share this resource


Discovered 2026-08-24 Source The Old New Thing Archive 2026-08 → c++templatesoptimization