도슐랭스타
C++ - 템플릿(Template) 본문
Generic programming
- 자료형이 나중에 결정되는 프로그래밍이다.
템플릿(Template)
- 매개변수를 통한 다형성을 제공한다.
- 코드는 전혀 바뀌지 않고 형만 다른 함수가 필요하다면 함수중첩 대신 템플릿을 사용하는 것이 좋다.
- 매개변수의 자료형과 값을 인자로 받아 함수를 생성시키는 포괄적 함수(generic function)이다.
템플릿 사용이유
#include <iostream>
using std::cout;
using std::endl;
int Min(int i, int j)
{
return i<j ?i:j;
}
double Min(double i, double j)
{
return i<j ?i:j;
}
char Min(char i, char j)
{
return i<j ?i:j;
}
int main()
{
cout<< "Min값은=" << Min(1,2)<<endl;
cout<< "Min값은=" << Min(7.5,3.6)<<endl;
cout<< "Min값은=" << Min('A','B');
return 0;
}
위와 같은 함수오버로딩(함수중첩)의 코드에서 Min()이라는 함수는 자료형만 다르지 모든 기능이 똑같다.
이런 경우 사용하는 것이 "template"이다.
#include <iostream>
using std::cout;
using std::endl;
template <class T> //<class T> 대신에 <typename T>로 써도 됨. T말고 다른 것도 가능.
T Min(T i, T j)
{
return i < j ? i : j;
}
int main()
{
cout << "Min값은=" << Min(1, 2) << endl;
cout << "Min값은=" << Min(7.5, 3.6) << endl;
cout << "Min값은=" << Min('A', 'B');
return 0;
}
template을 사용하여 자료형을 나중에 결정할 수 있다.
템플릿 객체
#include <iostream>
using std::cout;
using std::endl;
template <class T> //<typename T>도 가능.
class CCC
{
T x;
T y;
public:
CCC(T xx, T yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
int main()
{
CCC<int> c1(10, 20); //<int>
CCC<double> c2(3.5, 5.5); //<double>
CCC<char> c3('I', 'L'); //<char>
c1.Print();
c2.Print();
c3.Print();
return 0;
}
객체에서 자료형을 나중에 결정하고 싶다면 템플릿 사용 후 "<>"안에 자료형을 적어줘야한다.
★자료형이 2종류인 템플릿 객체
1) 템플릿X 코드
#include <iostream>
using std::cout;
using std::endl;
class CCC1
{
int x;
int y;
public:
CCC1(int xx, int yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
class CCC2
{
double x;
double y;
public:
CCC2(double xx, double yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
class CCC3
{
char x;
const char* y;
public:
CCC3(char xx, const char* yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
int main()
{
CCC1 c1(10, 20);
CCC2 c2(3.5, 5.5);
CCC3 c3('I', "Love You!");
c1.Print();
c2.Print();
c3.Print();
return 0;
}
2) 템플릿O 코드
#include <iostream>
using std::cout;
using std::endl;
template <class T1, class T2> //<typename T1, typename T2>도 가능.
class CCC1
{
T1 x;
T2 y;
public:
CCC1(T1 xx, T2 yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
int main()
{
CCC1<int, int> c1(10, 20);
CCC1<double, double> c2(3.5, 5.5);
CCC1<char, const char*> c3('I', "Love You!");
c1.Print();
c2.Print();
c3.Print();
return 0;
}
STL(Standard Template Library)
- C++ 표준라이브러리의 일부분이다.
- 자료구조 클래스와 알고리즘 등을 미리 만들어 놓은 라이브러리이다.
STL의 주요 구성 요소
- 컨테이너(container)
- 반복자(iterator)
- 알고리즘(algorithm)
- 함수 객체(function object), 함수자(function)
★예외처리(exception handling, error handling)
- 실행할 때 나는 오류를 잡는 것이다.
- try -> throw -> catch의 순서로 예외처리를 한다.
- try : 예외를 감시할 부분을 블록으로 묶는다.(main()함수 전체도 묶기 가능.)
- throw : 예외 발생시 예외 발생을 알리고 던진다.
- catch : 예외를 받아서 처리하는 블록이다.
1) 예외처리가 되지 않은 코드
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void Div(double ja, double mo)
{
cout << "결과:" << ja / mo << endl;
}
int main()
{
double x, y;
cout << "분자를 입력하세요=";
cin >> x;
cout << "분모를 입력하세요=";
cin >> y;
Div(x, y);
return 0;
}
2) 예외처리가 된 코드
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void Div(double ja, double mo)
{
try { //1
if (mo == 0 || ja == 0) throw mo; //2
cout << "결과:" << ja / mo << endl;
}
catch (double) { //3
cout << "오류:나누기 오류(분자나 분모 0)." << endl;
}
}
int main()
{
double x, y;
cout << "분자를 입력하세요=";
cin >> x;
cout << "분모를 입력하세요=";
cin >> y;
Div(x, y);
return 0;
}
반응형
'C++' 카테고리의 다른 글
C++ - 콘솔파일입출력 (0) | 2023.12.13 |
---|---|
C++ - 바인딩(binding) (1) | 2023.12.06 |
C++ - 다중상속의 문제점(다이아몬드 문제) (0) | 2023.12.01 |
C++ - overriding, 가상함수(virtual function) (0) | 2023.11.29 |
C++ - 다중 상속 (0) | 2023.11.29 |
Comments