How to compile template parameters without type?

I have a clear idea on how to compile template parameters. But won't non-type templates compile in the same way?

For example, with a type-type like this:

template<typename T> class TemplatedClass { ..do something with T.. }; TemplatedClass<int> IntClass; TemplatedClass<char> CharClass; 

The above will be compiled to separate class definitions for int and char:

 class TemplatedClass<int> { ..do something with int.. }; class TemplatedClass<char> { ..do something with char.. }; 

When configuring non-pig type parameters, does the compiler do this the same way? For instance:

 template<int N> class NumericClass { int array[N]; ..do something else with N.. }; NumericClass<3> Class3; NumericClass<5> Class5; 

Will this generate separate class definitions for each of the numeric values, as shown below?

 class NumericClass3 { int array[3]; ..do something else with 3.. }; class NumericClass5 { int array[5]; ..do something else with 5.. }; 

If so, could this lead to a ton of bloated compiled code if there are a significant number of numerical possibilities for the template parameter? I can have a static array class defined using a numerical pattern in my main API. Then each time I declare an instance with a unique length value, it would have to compile a new class definition for it. This can lead to a ridiculously large number of compiled definitions, assuming my code is open.

As far as I know, this is still encouraged by practice. Does the compiler have another way to work with non-type templates? Or is the overhead of being structured this way not that significant?

+6
source share
1 answer

Each instance of the template is conceptually a different object. The compiler can create different codes for each instance. It does not matter if the template arguments are type or non-type arguments. The compiler can share the code between different instances and give different characters to the same object code, but, of course, there is no mandate for this (for characters, some storage is still required until the code is linked).

As a result, it may be important to structure implementations in such a way as to minimize code specific to template arguments. For example, it may be prudent to encode code common to multiple instances into a base class (provided that the functionality must be a member function). For the remaining code, it is reasonable to make it fairly small so that it can be embedded and not generate any overhead if it is less than the code needed to call functions and return from them.

+3
source

All Articles