I know the template can't occupy memory in the run-time if I can't specialized it.
For example:
//code 1
template<typename T>
class foo {
T val;
}
If typename is int, only generate following code:
//code 2
template<typename T>
class foo {
int val;
}
The code 1 cannot be generate, so code cannot occupy memory in the run-time .
Now I specialized code 1
//code 3
template<>
class foo<double> {
double val;
}
Does code 3 occupy memory in the run-time?
You can check such questions with https://godbolt.org/ :
template<typename T>
struct foo {
foo(T v) : val(v) {}
T val;
};
template<>
struct foo<int> {
foo(int v) : val(v) {}
int val;
};
template<>
struct foo<double> {
foo(double v) : val(v) {}
double val;
};
int main() {
foo<int> a(5);
foo<short> b(10);
return a.val + b.val;
}
This code was compiled with clang (trunk) -O0. The output is
main: # @main
push rbp
mov rbp, rsp
sub rsp, 16
mov dword ptr [rbp - 4], 0
lea rdi, [rbp - 8]
mov esi, 5
call foo<int>::foo(int)
lea rdi, [rbp - 16]
mov esi, 10
call foo<short>::foo(short)
mov eax, dword ptr [rbp - 8]
movsx ecx, word ptr [rbp - 16]
add eax, ecx
add rsp, 16
pop rbp
ret
foo<int>::foo(int): # @foo<int>::foo(int)
push rbp
mov rbp, rsp
mov qword ptr [rbp - 8], rdi
mov dword ptr [rbp - 12], esi
mov rax, qword ptr [rbp - 8]
mov ecx, dword ptr [rbp - 12]
mov dword ptr [rax], ecx
pop rbp
ret
foo<short>::foo(short): # @foo<short>::foo(short)
push rbp
mov rbp, rsp
mov qword ptr [rbp - 8], rdi
mov word ptr [rbp - 10], si
mov rax, qword ptr [rbp - 8]
mov cx, word ptr [rbp - 10]
mov word ptr [rax], cx
pop rbp
ret
As you can see only the methods that are actually used are created.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.