r/cpp • u/pavel_v • Aug 22 '26
Reducing C++ template bloat by factoring out the type-dependent portions of the function
https://devblogs.microsoft.com/oldnewthing/20260820-00/?p=112629
103
Upvotes
34
u/sweetno Aug 22 '26
I can't wait to be shocked and amazed.
13
u/fdwr fdwr@github 🔍 Aug 22 '26
I also do this when encountering large templated functions, but I wonder how effective link-time function deduplication is now. If you had function in a templated class with a function that wasn't actually dependent on the type, or even if the function was dependent on the type but not in a meaningful way (for example, say it just mov'd some uint32_t's or int32_t's around, which likely yield the same asm), then would the linker successfully debloat things? (granted, I know that eliminating it before it even reaches the linker reduces linkage time)
6
u/Gungan_Boss_Nass premature cleverization Aug 23 '26
It's good reading (as are all the Chen articles) but reducing code size these days barely makes the "nice to have" category. We went all-in with code explosion when we set a full-steam course into metaprogramming, now it's a bit like trying to reduce the number of freeways in LA.
I'm more worried about "goal bloat" and the toxicity of conflicting goals. I'd probably criticize a lambda if some of its complexity was due to optimizing for this, unless it was for an embedded system with memory pressure.
4
u/Ok_Independence_9841 Aug 22 '26
Template bloat is a real thing. However it's got massively better over the years. When I first got tuples 'working' in 2003 they were utterly impractical due to the code bloat from recursive template bases. 100's of KB of object file and several seconds of compilation time for a single instantiation of tuple<int, int, int>.
Tuples were limited to a handful of elements or you'd get an ICE. You did anyway if you pushed your luck by doing anything like putting one tuple inside another. It's good to remember how far we've come, even if we aren't exactly there yet, and to appreciate pioneers like Jaakko Järvi who introduced tuples in C++. The first real technical advance on what Alex Stepanov did with templates in the STL.
2
u/fb39ca4 Aug 23 '26
If runtime performance isn't as critical just use std::function_ref.
2
u/jnordwick Aug 22 '26
You have to give up inlining for this. Not airways a win.
2
u/ts826848 Aug 22 '26
IIRC it's technically possible for the Rust compiler to apply a similar transformation on its own, though it doesn't do so right now. Are C++ compilers allowed to make the same transformation on their own, or does something about C++ semantics (explicit instantiations maybe?) preclude such a thing?
-8
u/trad_emark Aug 22 '26 edited Aug 23 '26
blog post, from microsoft, and does not scream ai.
i am shocked - in a good way ;)
(edit: i dont understand why i got so many downvotes. my comment was meant as a praise for the blog post. well, doesnt matter...)