HACKER Q&A
📣 Konohamaru

Do C++ templates result in a combinatorial explosion?


1. I read that C++ templates work by replacing each type variable with a specific type and generating the following function. Depending on how many types are called with each template call, that looks like it could generate a combinatorial explosion. Do they?

2. Does the parametric polymorphism of Rust result in the same combinatorial explosion? Does Rust's parametric polymorphism just generates ad-hoc polymorphic code?


  👤 hedora Accepted Answer ✓
They can cause a combinatorial explosion, though note that the compiler won’t instantiate functions that aren’t invoked.

Instantiating the same template the same way in multiple compilation units can get you another multiplicative factor. I’m not sure if link time optimization de-duplicates the result or not.

The main practical problem with this (other than big binaries) is that you can exhaust the instruction cache on your machine, which slows things down significantly.

I’m not sure how rust code generation works.

Apparently, one of the central design tenants of swift was to keep the compiled binary small, since it preserves instruction cache. This matters a lot when you have many different programs running (such as on an iPhone). Also, instruction cache thrashing is terrible for energy efficiency.