I have heard about code bloats in context of C++ templates. I know that is not the case with modern C++ compilers. But, I want to construct an example and convince myself.
Lets say we have a class
template< typename T, size_t N >
class Array {
public:
T * data();
private:
T elems_[ N ];
};
template< typename T, size_t N >
T * Array<T>::data() {
return elems_;
}
Further, let's say types.h
contains
typedef Array< int, 100 > MyArray;
x.cpp
contains
MyArray ArrayX;
and y.cpp
contains
MyArray ArrayY;
Now, how can I verify that the code space for MyArray::data()
is same for both ArrayX
and ArrayY
?
What else I should know and verify from this (or other similar simple) examples? If there is any g++ specific tips, I am interested for that too.
PS: Regarding bloat, I am concerned even for the slightest of bloats, since I come from embedded context.
Addition: Does the situation change anyhow if the template classes are explicitly instantiated?
The templates are especially harmful, since they generate code bloat across two dimensions: across template parameters and across translation units. In my opinion, the overuse of templates today is caused by modern trends in C++.
C++ templates can't use normal run-time C++ code in the process of expanding, and suffer for it: for instance, the C++ factorial program is limited in that it produces 32-bit integers rather than arbitrary-length bignums.
The main type of templates that can be implemented in C are static templates. Static templates are created at compile time and do not perform runtime checks on sizes, because they shift that responsibility to the compiler.
What Does Code Bloat Mean? Code bloat is code that is allegedly too long or slow on most computer systems. While the term usually refers to source code that is too long, it can also refer to executables that might be considered excessively large.
You're asking the wrong question - any "bloat" in your example has nothing to do with templates. (the answer to your question, btw, is to take the address of the member function in both modules and you'll see they're the same)
What you really want to ask is, for each template instantiation, does the resulting executable grow linearly? The answer is no, the linker/optimizer will do magic.
Compile an exe that creates one type:
Array< int, 100 > MyArray;
Note the resulting exe size. Now do it again:
Array< int, 100 > MyArray;
Array< int, 99 > MyArray;
And so on, for 30 or so different versions, charting the resulting exe sizes. If templates were as horrible as people think, the exe size would grow by a fixed amount for each unique template instantiation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With