반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Algorithm
- 예제
- 문법
- STL
- Biconnected_Component
- class_template
- qsort
- 총정리
- '0'
- c++
- singly Linked List
- 구현
- list
- 13305
- sort
- deletion
- function_template
- connected_component
- Critical_Path_Analysis
- Heap
- data_structure
- template
- 백준
- 알고리즘
- 자료구조
- 5397
- Pair
- Articulation_Point
- sstream
- red-black tree
Archives
- Today
- Total
- Today
- Total
- 방명록
어제의 나보다 성장한 오늘의 나
[c++] Template(템플릿) 총 정리 & 예제 본문
반응형
queue를 구현 하는데 int 타입만 담는 queue만을 구현 하지 않고
string을 위한 queue, char를 위한 queue 등, 상황에 따라 여러 type을 담을 수 있는
queue를 구현 하기 위해 공부하게 되었다.
<Template>
함수나 클래스가 여러 가지 타입에서 사용 될 수 있도록
함수나 클래스의 타입을 상황에 맞게 사용할 수 있도록 도와주는 것.
(type : int , double , string , char 등등)
종류
함수 템플릿 (function template) 과 클래스 템플릿 (class template)으로 나뉜다.
사용법
template <typename T>
or
template <class T1 , class T2>
위 처럼 여러개를 넣을 수도 있고
typename , class 모두 사용가능 하다.
① 함수 템플릿 사용법
함수 선언
template <typename T>
T sum(T a , T b){
return a+b;
}
main에서
int a = 1 , b = 2;
cout << sum<int> (a,b) << endl;
or
string s1 = "hello ";
string s2 = "world.";
cout << sum<string> (s1,s2) << endl;
template으로 2개 이상의 type을 동시에 사용하는 경우
template<class T1 , class T2>
void print(T1 a , T2 b){
cout << a << endl;
cout << b << endl;
}
※ 이 경우에는 T1, T2 가 어떤 타입인지 명확하게 알려주지 않고
그냥 변수들을 집어넣으면 컴퓨터가 알아서 해석한다.
main에서
int a = 1;
string s1 = "hello "
print(a,s1);
<int> , <string> 없이도 잘 출력된다.
2) 클래스 템플릿 사용법
template <typename T>
class queue{
private:
T val; //template 변수
public :
queue(T v){
val = v;
}
~queue(){}
// template 타입 반환 함수
T getVal() {
return val;
}
void printVal(){
cout << val << endl;
}
};
main Coding
int main(int args, char** argv){
queue<int> q(10); // int로 정의 , val = 10
cout << q.getVal() << endl;
q.printVal();
}
반응형
'c++ > 문법' 카테고리의 다른 글
[C++] Unique 함수 정리 및 예제 (0) | 2022.02.13 |
---|---|
[c / c++] new / malloc / calloc /realloc 총 정리 & 예제 (0) | 2022.02.12 |
[c++] [자료형] int / double / char / float 크기 (0) | 2022.02.12 |
[C++] Sort 와 Compare 함수 (Greater , less) (0) | 2022.02.10 |
[C++] Pair 와 Tuple (0) | 2022.02.10 |
Comments