Alex Rivera | Logout

C++ Templates: Convincing self against code bloat

Asked 2010-05-27T04:15:17.390
17

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?

Edit
Report

1 Answer

5

A better illustration of code bloat with templates is using a template to generate code, not variables. The typical panic is due to the compiler generating code for each instance of the template (stencil). This is similar to code bloat due to inline functions and methods. However, modern compilers and linkers can perform magick to reduce code size, depending on the optimization settings.

For example:

template <typename Any_Type>
void Print_Hello(const Any_Type& v)
{
    std::cout << "Hello, your value is:\n"
              << v
              << "\n";
    return;
}

The above code is best thought of as a stencil. The compiler will generate the code depending on the type passed to Print_Hello. The bloat here is that very little of the code is actually dependent on the variable. (Which can be reduced, by factoring out const code & data.)

The fear is that the compiler will generate the code for each instantiation using the same variable type, thus building up repetitive code:

int main(void)
{
  int a = 5;
  int b = 6;
  Print_Hello(a); // Instantiation #1
  Print_Hello(b); // Instantiation #2
  return 0;
}

The fear could also be extended when the template (stencil) is instantiated in different translation units.

Modern compilers and linkers are smart. A smart compiler would recognize the template function call and convert into some unique mangled name. The compiler would then only use one instantiation for each call. Similar to function overloading.

Even if the compiler was sloppy and generated multiple instances of the function (for the same type), the linker would recognize the duplicates and only put one instance into the executable.

When used wrecklessly, a function or method template can add extra code. Examples are large functions that only differ by type in a few areas. They have a

answered 2010-05-27T19:13:19.270

Your Answer