Michael
Michael

Reputation: 7809

(Can I minimize the) Footprint of template in my C++ Code?

I have a large class which basically handles one buffer of variable (numeric) datatype. So it seems a good choice to use a class template with this datatype as the only parameter. I'm not experienced in C++ and I wonder/worry a bit about the "footprint" such a template makes in my code.

There are three implications of templates which in my (C++ unexperienced) eyes are not necessary and make code ugly. I tried to avoid them, but neither did I find a good example how to do it nor did I manage to find it out by myself.

So the goal of this question is: Can you either confirm the following statements or give a counterexample?

  1. When using a class template, all class methods have to go into the header file. Even if they have no templated type in their interface or implementation.
  2. When using a static method or member of the class, I always have to specify a template parameter (MyClass< double > :: MY_STATIC), even if the templatization does not affect any of the static properties of the class.
  3. When using the class as a parameter for a function, I always have to give a template parameter, even when this function does not access any of the templated members? (function myFunc(MyClass< double> & myClass){ do something } )

Upvotes: 0

Views: 145

Answers (2)

Zsolt
Zsolt

Reputation: 582

As a general rule, don't have functions/data members in a template class which does not use the template parameters. Have a base class, put all non-template related things there, your template class should derive from it.

To answer your questions:

  • yes, everywhere where you need to instantiate the template, you need to see the full definition of the class and it's functions
  • yep, but put that into the base class
  • yes, see above

EDIT: One of the reasons to move to base class is code bloating (this expression actually exist, you can google it for more info): If you don't move the template unrelated code to a base class, the very same template independent code will be copied for all instantiation of your template, which means a lot of unnecessary code. If you put it to a base class, you will only have this code once.

Upvotes: 3

Erbureth
Erbureth

Reputation: 3423

  1. Yes. On the plus side, the code is only generated when the metod is actually used for the specialization.

  2. Yes. However, there is no (other then design choice) need for a static method to be a memeber of the templated class if it has no use for the templated parameter.

  3. Yes. The size and memory layout of the structure is determined by the template parameter.

Upvotes: 1

Related Questions