열혈 c++ 프로그래밍을 보고 요약정리합니다.
12장은 생략
template <typename T>
T Add(T num1, T num2)
{
return num1 + num2;
}
int main(void) {
cout << Add<int> (15, 20) << endl; //Add(15, 20)
cout << Add<double> (2.9, 3.7) << endl; //Add(2.9, 3.7)
cout << Add<int> (3.2, 3.2) << endl; //Add(3.2, 3.2)
cout << Add<double> (3.14, 2.75) << endl; //Add(3.14, 2.75)
return 0;
}
#include <iostream>
using namespace std;
template <typename T>
T Add(T num1, T num2)
{
cout << "T Add(T num1, T num2)" << endl;
return num1 + num2;
}
int Add(int num1, int num2)
{
cout << "Add(int num1, int num2)" << endl;
return num1 + num2;
}
double Add(double num1, double num2)
{
cout << "Add(double num1, double num2)" << endl;
return num1 + num2;
}
int main(void)
{
cout << Add(5, 7) << endl;
cout << Add(3.7, 7.5) << endl;
cout << Add<int>(5, 7) << endl;
cout << Add<double> (3.7, 7.5) << endl;
return 0;
}
다음의 코드는 컴파일러에게 char* 형 템플릿 함수가 필요한 경우에는 별도로 만들지 말고 해당 코드를 사용하라는 의미
temlate <>
char * Max<char*>(char * a, char * b)
{
cout << "char* Max<char*>(char* a, char* b)" << endl;
return strlen(a) > strlen(b) ? a : b;
}
template <typename T>
class Point
{
private:
T xpos, ypos;
public:
Point(T x = 0, T y = 0) : xpos(x), ypos(y)
{}
void ShowPosition() const
{
cout << '[' << xpos << ", " << ypos << ']' << endl;
}
};
int main(void) {
Point<int> pos1(3, 4);
pos1.ShowPosition();
Point<double> pos2(2.4, 3.6);
pos2.ShowPosition();
Point<char> pos3('P', 'F');
pos3.ShowPosition();
return 0;
}
//PointTemplate.h
#infdef __POINT_TEMPLATE_H_
#define __POINT_TEMPLATE_H_
template <typename T>
class Point
{
private:
T xpos,ypos;
public:
Point(T x=0, T y=0);
void ShowPosition() const;
};
#endif
//PointTemplate.cpp
#include<iostream>
#include "PointTemplate.h"
using namespace std;
template <typename T>
Point<T>::Point(T x, T y) : xpos(x), ypos(y)
{}
template <typename T>
void Point<T>:: ShowPosition() const
{
cout << '[' << xpos << ", " << ypos << ']' << endl;
}
//PointMain.cpp
int main(void) {
Point<int> pos1(3, 4);
pos1.ShowPosition();
Point<double> pos2(2.4, 3.6);
pos2.ShowPosition();
Point<char> pos3('P', 'F');
pos3.ShowPosition();
return 0;
}