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>;
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++”.