Reputation: 3415
I was wondering whether you should worry about the number of class template instantiations and their effect on compile times. In the below example, I imagined that the Foo template would only be instantiated only once, while the Bar template would be instantiated twice. Do such differences matter to STL writers?
template<unsigned SIZE>
struct Foo
{
const unsigned size_;
Foo() : size_(SIZE) {}
};
Foo<1> foo1;
Foo<2> foo2;
template<unsigned SIZE>
struct Bar
{
static constexpr unsigned size_{SIZE};
};
Bar<1> bar1;
Bar<2> bar2;
I'm feeling like I'm wrong about the Foo template being instantiated only once. If so could you tell me whether
Bar<1> bar1;
Bar<1> bar2
...
Bar<1> bar10000;
would instantiate the Bar
template once or 10,000 times.
Class templates instantiate types, types instantiate objects, does reducing the number for instantiated types matter if the number of objects instantiated remain the same?
Are such things even relevant to compile times (I doubt they would be for my purposes)
Upvotes: 1
Views: 134
Reputation: 207
Actually you are creating objects: Bar<1> bar1; Bar<1> bar2 ... Bar<1> bar10000; 10000 times => instantiation during run time. Not during compile time. Compiler used to compile, check programming, create executable file. Once compiled without any error, during execution, objects are created based on the code flow. Handle memory management when creating objects to handle performance issues(if any) during run time. you can identify that using: (Example:) cout inside constructors to know how many times the constructors being called.
Upvotes: -1
Reputation: 33864
So the simple answer is that the generation of template code (and subsequent compilation) will occur for each type you are creating. So in this example:
Bar<1> bar1;
Bar<1> bar2
...
Bar<1> bar10000;
Each of these are of type Bar<1>
so you only need to generate the code for Bar<1>
once. You can see this in the cpp insights tool.
This will change however, if you use this across your code base. Remember that each translation unit (somewhat analogous to cpp file) that includes this header will redefine the types Bar
and Foo
for any number they are used with. If this is the case, you may find your code being generated and compiled a lot. For this simple template that is not a concern, but for much more complex templates, that may depend on other templates, this can quickly add up.
Upvotes: 2