부가적인 상황들
1. 서로 다른 매개변수를 동시 받을 경우(function with two generic types)
int int를 받거나
char char를 받는 것이 아닌,
int char를 받을 때는 어떻게 되나 궁금하던 찬라,
바로 다음 예시에 나왔다.
template class를 그 수만큼 선언해주고 쓰면된다.
아래 소스코드 참조
소스보기 소스닫기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using
namespace
std;
template
<
class
type1,
class
type2>
void
myfunc(type1 x, type2 y){
cout<<
"x: "
<<x<<
" y: "
<<y<<endl;
}
int
main(){
myfunc(10,
"hi"
);
myfunc(0.24, 10L);
return
0;
}
소스닫기
책에 나와 있는 예시에서는 10L을 넣었는데, 왜 10만 출력되는지.. 그건 잘 모르겠다 xcode로 컴파일 했을때만 10이라고 나오는건지, 원래 저자의 의도가 안되는걸 보여주려고 했던건지..
2. 한개의 타입에 대해서만 다른 수행을 하고 싶을 때(explicitly overloading a generic function)
소스보기 소스닫기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using
namespace
std;
template
<
class
X>
void
swapargs(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
cout<<
"template swap success"
<<endl;
}
void
swapargs(
int
&a,
int
&b)
{
int
temp;
temp = a*100;
a = b*100;
b = temp;
cout<<
"integer swap success!"
<<endl;
cout<<
"caution: value is mulitpled by 100"
;
}
int
main()
{
int
i=10, j=20;
double
x=10.1, y=23.3;
char
a=
'x'
, b=
'z'
;
cout<<
"i,j "
<<i<<
' '
<<j<<endl;
cout<<
"x,y "
<<x<<
' '
<<y<<endl;
cout<<
"a,b "
<<a<<
' '
<<b<<endl;
swapargs(i,j);
swapargs(x,y);
swapargs(a,b);
cout<<
"swap 후..........."
<<endl;
cout<<
"i,j "
<<i<<
' '
<<j<<endl;
cout<<
"x,y "
<<x<<
' '
<<y<<endl;
cout<<
"a,b "
<<a<<
' '
<<b<<endl;
return
0;
}
소스닫기
오버로딩을 혼합해준다.
3. 단순 template함수 overloading
소스보기 소스닫기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using
namespace
std;
template
<
class
X>
void
myfunc(X a){
cout<<
"1번이 콜 되었음"
<<endl;
}
template
<
class
X>
void
myfunc(X a, X b){
cout<<
"2번이 콜 되었음!"
<<endl;
}
int
main(){
myfunc(10);
myfunc(10, 20);
return
0;
}
소스닫기
4. generic class
소스보기 소스닫기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
using
namespace
std;
const
int
SIZE = 100;
template
<
class
Qtype>
class
queue{
Qtype q[SIZE];
int
sloc, rloc;
public
:
queue(){ sloc = rloc = 0;}
void
qput(Qtype i);
Qtype qget();
};
template
<
class
Qtype>
void
queue<Qtype>:: qput(Qtype i)
{
if
(sloc==SIZE)
{
cout<<
"queue is full\n"
;
return
;
}
sloc++;
q[sloc] = i;
}
template
<
class
Qtype> Qtype queue<Qtype>::qget(){
if
(rloc == sloc){
cout<<
"queue is underflow\n"
;
return
0;
}
rloc++;
return
q[rloc];
}
int
main(){
queue<
int
> a,b;
a.qput(10);
b.qput(19);
a.qput(20);
b.qput(1);
cout<<a.qget()<<
" "
;
cout<<a.qget()<<
" "
;
cout<<b.qget()<<
" "
;
cout<<b.qget()<<
" "
;
cout<<a.qget()<<
" "
;
cout<<b.qget()<<
" "
;
return
0;
}
소스닫기