Boost logo

Boost Users :

From: Gottlob Frege (gottlobfrege_at_[hidden])
Date: 2005-05-18 22:58:18


> Date: Wed, 18 May 2005 17:32:49 -0700
> From: "Elisha Berns" <e.berns_at_[hidden]>
> Subject: [Boost-users] Question about template optimization
> To: "Boost" <boost-users_at_[hidden]>
> Message-ID: <000001c55c0a$4966cf30$651aa8c0_at_INSPIRATION>
> Content-Type: text/plain; charset="us-ascii"
>
> I need help with this one, even though it's a pure C++ question, it's
> about template optimization:
>
> If a template class has methods that DO NOT depend on or use the type
> parameter(s) of the template will the code for the methods nevertheless
> get instantiated separately for each unique instance of the template
> class? For example, if there are 20 unique types used to declare 20
> instances of template class X, do those methods get implemented 20
> different times, needlessly, and cause a big code bloat?
>

what about 'non-dependent' methods with local statics:

template <typename T> class C
{
   int fooCount()
   {
        static int foo = 0;
        return ++foo;
   }
};

C<int> a;
C<long> b;

int fooA = a.fooCount();
int fooB = b.fooCount();

what is the value of fooB?

If there was only 1 implementation of fooCount() I would expect fooB
== 2. However, I think you will find fooB == 1.

I suppose a compiler could still make the code common, but with
separate static foo's, but then in general, there is nothing stopping
a compiler from looking at 2 unrelated functions and saying, 'hey,
lots of the code here looks the same; I should just refactor some of
it out and remove some code bloat'. Not sure much of that ever
happens. Reality is that once upon a time there were compiler
switches for size vs speed, but speed won.

> Even if most compilers are smart about this kind of thing, is it still
> better practice to separate from the template class (or method) all of
> the code that does not use the template type parameters?
>

Short answer: I suspect code bloat happens, and you should keep
non-dependent code out of your templates if you care about it enough.

> Thanks,
>
> Elisha Berns
> e.berns_at_[hidden]
>
>

Tony


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net