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?
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.