[C++]템플릿(Template) - 함수 템플릿, 클래스 템플릿, 템플릿의 특수화
//*****************************************************************************
// 템플릿 (template)
//*****************************************************************************
// 일반화 프로그래밍
// 하나의 함수혹은 클래스에서 여러가지 경우를 모두 처리하는 프로그래밍 기법!
// 여러가지 경우라 함은 로직은 같지만 타입 때문에 여러개로 정의해야 하는 경우 

#템플릿이란?

기능은 결정되어 있으나 자료형이 정해져 있지 않는 것을 템플릿 이라고 한다. 예을 들어 계산기 프로그램의 덧셈 함수를 만들때 해당 자료형에 맞는 함수를 오버로딩해야 한다. 하지만 템플릿으로 만든 함수는 그럴 필요가 없이 하나의 함수로 모두 사용이 가능하다.

 

#함수 템플릿(Function Template)

template <typename 식별자> 함수()  // 함수 앞에 사용. 식별자는 자료형을 의미하는 것으로 적용할 자료형에 사용하면 된다.

참고사항> typename을 class 로 대체 가능하다.  ex> template <class T>

ex>

template <typename T>  // 두줄로 해도 상관 없다.

T Add(T a, T b)

{

  return a+b;

}

  int  p = Add(1,3);  // int형 4을 반환 한다.

  int  p = Add<int>(1,3);  // 명시적으로 <자료형>을 같이 써주어도 된다. 위와 동일하게 동작한다.

  double q = Add(1.1,3.3);  // double형 4.4을 반환한다.

  CString str1 = "abcd", str2 = "EFGH", str;

  str = Add(str1, str2);  // CString형 "abcdEFGH"를 반환 한다.

 

위와 같이 자료형은 다르지만 하나의 함수로 이것을 가능하게 해주는 것이 템플릿이다. 물론 자료형이 같다고 되는 건 아니다. 예로 char*의 경우 포인터끼리 + 한다면 우리가 원하는 값이 나오지 않을 것이다. 이때 사용하는 것이 템플릿 특수화이다. CString 의 경우에는 + 연산자오버로딩이  되어있기 때문에 가능하다.


#include <iostream>
using namespace std;

template<class Any>
void Swap(Any &a,Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
template<class Any,class Any2>
void Swap(Any2 &a,Any &b)
{
Any2 temp;
temp = a;
a = b;
b = temp;
}
void main()
{
int x= 20,y=10;
cout << "befor int swap   " << "x =  " << x <<"  "<<"y =  "<< y << endl; 
Swap(x,y);
cout << "after int swap   " << "x =  " << x <<"  "<<"y =  "<< y << endl;
cout << endl;
char i = 'c',j='j';
cout << "befor char swap   " << "i =  " <<i << "  "<<"j =  "<< j << endl; 
Swap(i,j);
cout << "after char swap   " << "i =  " << i<<"  " <<"j =  "<< j << endl;
cout << endl;
double k=24.5,c=94.3;
cout << "befor double swap   " << "k =  " <<k << "  "<<"c =  "<< c << endl; 
Swap(k,c);
cout << "after double swap   " << "k =  " << k<<"  " <<"c =  "<< c << endl;
cout << endl;

double num1 =84.5;
int num2 = 50;
cout << "befor double swap   " << "num1 =  " <<num1 << "  "<<"num2 =  "<< num2 << endl; 
Swap(num1,num2);
cout << "after double swap   " << "num1 =  " << num1<<"  " <<"num2 =  "<< num2 << endl;
cout << endl;
}


'Programing > C++' 카테고리의 다른 글

가상함수테이블  (0) 2016.11.30
템플릿(Template) -클래스 템플릿, 템플릿의 특수화  (0) 2016.11.30
클래스  (0) 2016.11.30
구조체  (0) 2016.11.30
함수 오버로딩, SWAP  (0) 2016.11.30
#ifndef MYTIME
#define MYTIME
//****************************************************************************************
//클래스 선언
//****************************************************************************************
class Time
{
private:
int hours;
int min;
public:
Time();
Time(int h,int m = 0);
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0, int m =0);
Time operator+(const Time & t) const;
Time operator-(const Time & t) const;
Time operator*(const Time & t) const;
void Show() const;
}
#endif MYTIME

//****************************************************************************************
#include <iostream>
#include "ex2.h"

Time::Time()
{
Hours = minutes = 0;
}
Time ::Time(int h, int m )
{
hours =h;
min = m ;
}
void Time::AddMin(int m)
{
min += m;
hour += min/60;
mim %= 60;
}

void Time::AddHr(int h)
{
hours += h;
}

void Time::Reset(int h, int m)
{
hours = h;
min = m;
}

Time Time::operator +(const Time &t) const
{
Time sum;
sum.min = min +t.min;
sum.hours = hour + t.hours + sum.min / 60;
sum.min %= 60;
return sum;
}

Time Time::operator -(const Time &t) const
{
Time diff;
int tot1, tot2;
tot1 = t.min + 60 * t.hours;
tot2 = min + 60 * hours;

diff.min = (tot2 - tot1) % 60;
diff.hours = (tot2 - tot1) / 60;

return diff;
}

Time Time::operator *(const Time &t) const
{
Time result;
long totalmin = hours * mult * 60 + min * mult;
result.hours = totalmin / 60;
result.min = totalmin % 60;

return result;
}

void Time::Show() const
{
std::cout << hours << "시간," << min <<"분";
}
//****************************************************************************************
// main
#include <iostream>
#include "ex2.h"

void main()
{
using namespace std;

Time weeding(4, 35);
Time waxing(2,47);
Time total;
Time diff;
Time adjusted;

cout << "weeding time = ";
weeding.Show();
cout << endl;

cout << "waxing time =";
waxing.Show();
cout << endl;

cout << "total work time =";
total = weeding + waxing;
total.Show();
cout << endl;

diff = weeding - waxing;
cout << "weeding time - waxing time =";
diff.Show();
cout << endl;

adjusted = total * 1.5;
cout << "adjusted work time = ";
adjusted.Show();
cout << endl;
}


//**************************************************************************
//구조체 !!
//**************************************************************************
//정의 : 사용자 정의 데이터 타입 !!
//**************************************************************************
// 기본 타입으로 표현하기 힘든것들을 표현하기 위한 방법 !!
#include <iostream>
using namespace std;

class Person
{//속성
private :
int Number; // 번호
int age; // 나이
char name[20]; //이름
int stress; //스트레스
//행동
public :
int GetAge(){
return age;
}

char *GetName(){
return name;
}

void SetAge(int newage)
{
if(newage <= 0)
{
age = 1;
}
else
{
age = newage;
}
}

void speak(){
stress--;
}
void sleeping(){
stress--;
}
void play(){
stress--;
}
void fighting(){
}
void show(){
cout << Number << age << name << endl;
}

};
//접근 제한자!!
//private : 외부로부터 접근을 막는다.!!
//public : 내부 외부 모두에서 접근 할도록 지정 !!
//protected : 상속 : 외부에서는 접근할수 없고 오직 내부,자식에서만 접근 가능

void main()
{
Person LEE;
LEE.play();
int i =  0;
cin >> i;
LEE.SetAge(i);
cout << LEE.GetAge() << endl;
cout << LEE.GetName() << endl;

}


+ Recent posts