Domanda

If I use a template class to create 30 different definitions. My question is that will it compile into 30 actual classes in binary (binary size = sizeof(template_class) x 30), although their actual code are very similar or even exactly the same ?

And if it would, and during runtime, my program is load into memory. I loop through those 30 instances (assume i initialized 1 instance per definition), would it causes the cpu instruction cache to reload because they are actually 30 copies in memory, even most of their code are the same?

    template<typename msg_policy, int id>
    class temp_class_test : public msg_policy
            //codes, methods, and members
    };

    template class temp_class_test<A_policy,1>;
    template class temp_class_test<B_policy, 2>;
È stato utile?

Soluzione

As it stands, the classes instantiated from your template are distinct classes with distinct code. And yes, that would cause the code to be reloaded again and again at execution.

You can mitigate this the way Walter suggested in the comments: by having the implementation in some common base class that all other classes derive from. I went into some detail about this technique in my answer on the question on “How to define different types for the same class in C++”.

Altri suggerimenti

If your 30 odd classes are very similar, you should avoid code duplication. For example, the template parameter id may just be a stub to differentiate otherwise identical classes. In this case, you don't need to re-define the class for every id, but may simply inherit from an implementation:

namespace implementation {
  template<typename p> class test {
    // implementation
  };
}
template<typename p, int id>
class temp_class_test : public implementation::test<p>
{
   // any additional code dependent on id
   // any non-inheritable code (constructors)
};

The compiler will then only generate one binary for each method of the base class and the id merely serves to distinguish different temp_class_test.

Autopsy done. That is why my application perform so badly when my application is under stress. It was because my cpu was experienced forever cache miss.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top