티스토리 뷰

반응형

13-1 템플릿(Template)에 대한 이해와 함수 템플릿

템플릿의 사전적 정의는 '모형자'이다. 

모형자에 넣으면 원하는 모양이 나온다. 그러나 빨간색 파란색에 대한 것은 사용자가 정한다.

 

함수를 대상으로 템플릿 이해하기

'함수 템플릿은 함수를 만들어 낸다. 함수의 기능은 결정되어 있지만, 자료형은 결정되어 있지 않아서 결정해야 한다.'

 

int Add(int num1, int num2)

{

 return num1+num2;

}

함수의 기능 덧셈

대상 자료형 int형 데이터

 

T Add(T num1, T num2)

{

 return num1+num2;

}

함수의 기능 덧셈

대상 자료형 결정되어 있지 않음

 

template <typename T>

T Add(T num1, T num2)

{

 return num1+num2;

}

 

templete <typename T>를 사용하여 템플릿을 정의한다.

클래스의 경우 templete <class T>

 

int가 오면 int로 double이 오면 double으로 T 부분이 대체되서 실행된다.

int Add<int>(int num1, int num2)

{

 return num1+num2;

}

 

 

호출하기가 좀 불편한 건 있네요

Add(3.5, 4.5);

->double형으로 치환

 

함수 템플릿과 템플릿 함수

앞서 보인 정의를 함수 템플릿(function template)이라 한다.

 

템플릿을  기반으로 컴파일러가 만들어내는 함수->템플릿 함수(template function)

 

int Add<int>(int num1, int num2)

{

 return num1+num2;

}

double add<double>(double num1, double num2)

{

 return num1+num2;

}

 

둘 이상의 형(Type)에 대해 템플릿 선언하기

 

#include <iostream>
#include <string>

using namespace std;

template <class T1, class T2>
void ShowData(double num)
{
	cout << (T1)num << ", " << (T2)num << endl;
}

int main(void)
{
	ShowData<char, int> (65);
	ShowData<char, int>(67);
	ShowData<char, double>(68.9);
	ShowData<short, int>(69.2);
	ShowData<char, int>(70.4);
	return 0;
}

 

위에서 class는 객체를 생성할 때 만드는 class가 아니라 type name을 의미한다.

 

 

함수 템플릿의 특수화(Specialization)

#include <iostream>
#include <string>

using namespace std;

template <typename T>
T Max(T a, T b)
{
	return a > b ? a : b;
}

int main(void)
{
	cout << Max(11, 15)        << endl;
	cout << Max('T', 'Q') << endl;
	cout << Max(3.5, 7.5) << endl;
	cout << Max("Simple", "Best") << endl;
	return 0;
}

 

교재에서는 컴파일 결과가 Simple이 아니라 Best가 나오는데, 아마 2010년 버전과 2022년인 지금 컴파일러의 차이 탓에 그런 것 같다.

 

문자열 2개가 전달됐을때,

1) 문자열의 길이가 더 큰 것을 찾는지

2) 사전편찬의 순서 비교를 원하는 것인지

 

이에 따라 함수를 다르게 설정할 수 있다.

 

#include <iostream>
#include <cstring>

using namespace std;

template <typename T>
T Max(T a, T b)
{
	return a > b ? a : b;
}
template<>
char* Max(char* a, char* b)
{
	cout << "char* Max << char* > (char* a, char* b)" << endl;
	return strlen(a) > strlen(b) ? a : b;
}

template<>
const char* Max(const char* a, const char* b)
{
	cout << "const char*Max<<const char*>(const char* a, const* b)" << endl;
	return strcmp(a, b) > 0 ? a : b;
}

int main(void)
{
	cout << Max(11, 15)        << endl;
	cout << Max('T', 'Q') << endl;
	cout << Max(3.5, 7.5) << endl;
	cout << Max("Simple", "Best") << endl;

	char str1[] = "Simple";
	char str2[] = "Best";
	cout << Max(str1, str2) << endl;;

	return 0;
}

 

char*형 함수는 알아서 만들지말고 내가 제시한 함수를 써라.

-> template<>

 

 

13-2 클래스 템플릿(Class template)

#include <iostream>
#include <cstring>

using namespace std;

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();
}

 

템플릿으로 클래스도 정할 수 있다.

클래스에 들어갈 함수를 일일이 오버로딩 할 필요가 없다.

 

 

클래스 템플릿의 선언과 정의의 분리

template <typename T>

class SimpleTemplate

{

public:

 T SimpleFunc(const T& ref);

};

->선언

 

template <typename T>

T SimpleTemplate<T>::SimpleFunc(const T& ref)

{

}

함수 정의

 

 

파일을 나눌 때에는 고려할 사항이 있습니다.

헤더파일에 헤더파일의 선언과 멤버함수의 정의를 다 넣는다

or

다 include를 한다.

 

배열클래스의 템플릿화

->자료형을 배열 클래스에서도 T로 선언한다.

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
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
글 보관함
반응형