프로그래밍/C++

[C++ 문법] Template

준코딩 2019. 4. 2. 21:38

C++ 문법

 

Template

 

  개념부분은 내용을 조금씩 추가 할 예정입니다.

 

 

문법

 

template <class T>   or  template <typename T>

         1                 2     3

 

 

1 : 선언해주는 이름

 

2 : class, typename 두 가지의 경우가 있는데, 아무거나 사용해도 좋다. 하지만 class 의 경우 이미 정해진 이름이 있기 때문에 보통 typename 을 사용한다.

 

3 : 여기에는 편하게 사용할 문자를 사용하는데, 역시 보통 T 를 사용합니다.

 

 

 

코드 예시1)

: 같은 자료형인 두개의 인수를 받는 경우

 

1
2
3
4
5
6
template <typename T>
 
T add(T a, T b)
{
    return a + b;
}
cs

 

다시 return 하는 경우 당연히 함수도 T 로 선언해줘야 겠죠ㅎㅎ

 

 

코드 예시2)

: 다른 자료형인 두개의 인수를 받는 경우

 

 

1
2
3
4
5
6
7
template <class T1, class T2>
 
void print(T1 a, T2 b)
{
    cout << "T1 : " << a << endl;
    cout << "T2 : " << b << endl;
}
cs

 

지금은 return 값이 필요 없으므로 void로 선언됬습니다.

 

 

코드 예시3)

: T 자료형을 출력하거나 사용할때는 꼭 자료형을 표시해줘야 합니다.

 

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
#include <iostream>
#include <string>
 
using namespace std;
 
template <class T>
 
T add(T a, T b)
{
    return a + b;
}
 
int main() {
    
    int a = 1;
    int b = 2;
 
    float f1 = 12.0f;
    float f2 = 13.1f;
 
    string s1 = "해도해도 ";
    string s2 = "끝이 없다.";
 
    cout << "int 합 :" << add<int>(a, b) << endl;
    cout << "float 합 :"<< add<float>(f1,f2) << endl;
    cout << "string 합 : "<< add<string>(s1,s2) << endl;
 
 
    return 0;
}
cs