Reputation: 53
I read that templates are complied into different entities so does that mean the binary size will be same as we have complied it using different functions?
Upvotes: 5
Views: 493
Reputation: 16597
It depends ... If you were going to implement for each type a separate class then source code size will decrease.
As of for binary most probably you will not see any significant difference, because if you were going to implement separate class for each type and you didn't because you have used templates it doesn't mean that binary size will decrease, because that code will be generated by compiler (for the instantiations), so you must not have any significant difference because "code is the same".
Upvotes: 2
Reputation: 3690
My understanding is that for each type you instantiate with a template the complier produces the relevant class to match that type - so if you use List<int>
, List<foo>
and List<float>
there will effectively be three different List
classes in your complied binary.
Edit:
What I didn't explicitly state was that I'm inferring that merging several classes in to a single template will (probably) not reduce the size of your binary, but should reduce the size of your source.
Upvotes: 2
Reputation: 8074
Templates will definitely be a way to write more generic and shorter code. Instead of writing your function
blah
n times to deal with different types of parameters, you write it once with a generic type for the parameter.
Regarding the binary size, code will be generated for the instantiations you make of the template, that is, when you specify a type. I don't see how it would shorten binary sizes.
Upvotes: 0
Reputation: 208436
They should shorten the source size (if they are reused) but not the binary size (the template is compiled for each different instantiation).
This differs from Java generics, where there is a full type erasure (generics only serve as a compile time verification of types) or C#, where generics are compiled into specific binaries that can be directly reused without having to recompile and generate more code.
Upvotes: 5
Reputation: 246
The binary size depends on your compiler and the optimasations the compiler will perform to reduce the code size by elimnating redandant code.
Modern compilers are able to detect redundant code, so the binary size will not increase dramaticly by using templates.
Upvotes: 0