#include <stdio.h>
template<int N> class A {
public:
A() { a = N;}
int a;
};
int
main() {
A<10> *a = new A<10>();
printf("%d\n", a->a);
return 0;
}
type이 아니라, 변수 값을 전달할 수도 있다. 이 경우 장점은?
compile time에 값이 정해지므로 compiler가 code를 optimize할 수 있다.
예.
[ a. cpp ]
#include <stdio.h>
template<int N> class A {
public:
A(int n) { mN = n; }
void speak() {
if (N > 5)
printf("I'm BIG\n");
else
printf("I'm SMALL\n");
}
int mN;
};
int
main() {
A<10> *a = new A<10>(10);
A<2> *b = new A<2>(2);
a->speak();
b->speak();
return 0;
}
<< objdump >>
...
void speak() {
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 83 ec 10 sub $0x10,%rsp
8: 48 89 7d f8 mov %rdi,-0x8(%rbp)
if (N > 5)
printf("I'm BIG\n");
c: bf 00 00 00 00 mov $0x0,%edi
11: e8 00 00 00 00 callq 16 <_ZN1AILi10EE5speakEv+0x16>
else
printf("I'm SMALL\n");
}
16: c9 leaveq
17: c3 retq
...
void speak() {
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 83 ec 10 sub $0x10,%rsp
8: 48 89 7d f8 mov %rdi,-0x8(%rbp)
if (N > 5)
printf("I'm BIG\n");
else
printf("I'm SMALL\n");
c: bf 00 00 00 00 mov $0x0,%edi
11: e8 00 00 00 00 callq 16 <_ZN1AILi2EE5speakEv+0x16>
}
16: c9 leaveq
17: c3 retq
...
[ b. cpp ]
#include <stdio.h>
template<int N> class A {
public:
A(int n) { mN = n; }
void speak() {
if (mN > 5)
printf("I'm BIG\n");
else
printf("I'm SMALL\n");
}
int mN;
};
int
main() {
A<10> *a = new A<10>(10);
A<2> *b = new A<2>(2);
a->speak();
b->speak();
return 0;
}
<< objdump >>
...
void speak() {
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 83 ec 10 sub $0x10,%rsp
8: 48 89 7d f8 mov %rdi,-0x8(%rbp)
if (mN > 5)
c: 48 8b 45 f8 mov -0x8(%rbp),%rax
10: 8b 00 mov (%rax),%eax
12: 83 f8 05 cmp $0x5,%eax
15: 7e 0c jle 23 <_ZN1AILi10EE5speakEv+0x23>
printf("I'm BIG\n");
17: bf 00 00 00 00 mov $0x0,%edi
1c: e8 00 00 00 00 callq 21 <_ZN1AILi10EE5speakEv+0x21>
21: eb 0a jmp 2d <_ZN1AILi10EE5speakEv+0x2d>
else
printf("I'm SMALL\n");
23: bf 00 00 00 00 mov $0x0,%edi
28: e8 00 00 00 00 callq 2d <_ZN1AILi10EE5speakEv+0x2d>
}
2d: c9 leaveq
2e: c3 retq
...
void speak() {
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 83 ec 10 sub $0x10,%rsp
8: 48 89 7d f8 mov %rdi,-0x8(%rbp)
if (mN > 5)
c: 48 8b 45 f8 mov -0x8(%rbp),%rax
10: 8b 00 mov (%rax),%eax
12: 83 f8 05 cmp $0x5,%eax
15: 7e 0c jle 23 <_ZN1AILi2EE5speakEv+0x23>
printf("I'm BIG\n");
17: bf 00 00 00 00 mov $0x0,%edi
1c: e8 00 00 00 00 callq 21 <_ZN1AILi2EE5speakEv+0x21>
21: eb 0a jmp 2d <_ZN1AILi2EE5speakEv+0x2d>
else
printf("I'm SMALL\n");
23: bf 00 00 00 00 mov $0x0,%edi
28: e8 00 00 00 00 callq 2d <_ZN1AILi2EE5speakEv+0x2d>
}
2d: c9 leaveq
2e: c3 retq
...
===============================================
위의 코드를 보면, template 의 value를 사용할 경우, 'if'문에서, 사용되지 않는 코드가 compile시 object에 반영되지 않고 삭제되어 버리는 것을 알 수 있다.
즉 compile time에 충분히 optimize되어 버린다. (if 문의 condition이 compile time에 결정될 수 있으므로...)