Say we have a class A:
template<int N>
class A final{
public:
void foo() const { cout << N << endl; }
};
Where is the template parameter N stored? In the heap or in the object's memory in the stack?
N
itself is not stored anywhere, it is encoded into the type. From that point of view, a template specialization A<1>
is the same as a non-template class A1
. For A<2020>{}.foo()
you're likely to get the same assembly as for std::cout << 2020
. Of course, the constant 2020
has to be stored somewhere, but it will not be a part of A<2020>{}
object.
After compilation, depending on the target architecture, A<2020>{}.foo()
might look like this (x86-64):
mov esi, 2020
mov edi, OFFSET FLAT:_ZSt4cout
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
Here N
is put directly into the register.
Or (ARM):
ldr r1, .L4
ldr r0, .L4+4
bl std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
...
.L4:
.word 2020
.word _ZSt4cout
Here N
is loaded from some memory location.
Assembly demo
Generally, the good thing about using templates is that the templates themselves don't cost any run-time performance and also cost no memory space at run-time. They don't even exist at run-time anymore, because they have already been fully processed and evaluated at compile-time.
So, the only time when templates themselves cost performance and space is at compile-time.
However, the code that the templates generate at compile-time does of course cost space at run-time. If the templates are instantiated several times, then the code will be generated several times too, once for every set of template parameters that the program uses. This increase in code size can also affect performance negatively, because the CPU instruction cache can cache small amounts of code better than large amounts of code.
To answer your question:
At run-time, the templates themselves and their parameters are neither stored on the heap nor on the stack, because they don't even exist anymore. Only at compile-time will templates and their parameters be stored somewhere in the compiler's heap or stack. However, the internals of the compiler are of no interest to you (unless you plan to program your own compiler).
But, in your example, the value of N in your question will still be stored somewhere in your program. But it will not be stored as a template parameter, but rather as an immediate value stored in the executable code of your program as a result of the template being evaluated at compile-time. It may actually also be stored in your program's stack at some time, because, in your example, it is passed as a parameter for a function call. However, whether function parameters are passed on the stack or through a CPU register depends on what platform you are using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With