영넌 개발로그

[C++ 기초] Function template / Class template 본문

코딩/C++

[C++ 기초] Function template / Class template

영넌 2020. 12. 6. 20:08

Function template

여러가지 타입(type)을 동시에 처리 가능한 함수이다. 서로 인수의 타입이 다르고 같은 이름의 함수를 만드는 것 외에 다른 방법으로 Function template을 사용할 수 있다. 이를 통해 오버헤드를 줄일 수 있다.

default 타입도 지정해줄 수 있고, 여러개를 만들 수도 있다. default 타입은 마지막에만 지정해줄 수 있다.

사용법 : template<typename T,  typename T2=int>

 

예를 들어 integer에 대해서만 동작하는 함수 get_max가 있다고 해보자. 이 함수는 둘 중 큰 값을 반환한다.

이 때 double type 인수 5.8과 10.09를 넣으면 형 변환이 일어나고 10이 출력되게 된다. ( double형에서는 동작하지 않는다) 

#include <iostream>

using namespace std;

int get_max(int a, int b)
{
	return (a >= b) ? a : b;
}

int main() {

	cout << "bigger one is : " << get_max(5, 4) << endl;

	return 0;
}

 

위의 코드를 template을 이용하여 사용한다면 여러 타입에 대해서 한 함수를 이용할 수 있다.

#include <iostream>

using namespace std;

template<typename T>

T get_max(T a, T b) {
	return (a >= b) ? a : b;
}

int main() {

	cout << "bigger one is : " << get_max(5, 4) << endl;
	cout << "bigger one is : " << get_max(5.8, 10.9) << endl;

	return 0;
}

 

 

행동에 대해서 type에 따라 예외를 주고 싶을 때가 있다.

int와 double에서는 큰 값을 넘겨주지만 char형일 경우 작은 값을 넘겨주고 싶다면 아래와 같이 하면 된다.

같은 이름의 함수를 만들고 그 위에 template<> 을 적어준다.

#include <iostream>

using namespace std;

template<typename T>

T get_max(T a, T b) {
	return (a >= b) ? a : b;
}

template<>
char get_max(char a, char b) {
	return (a >= b) ? b : a;
}


int main() {

	cout << "bigger one is : " << get_max(5, 4) << endl;
	cout << "bigger one is : " << get_max(5.8, 10.9) << endl;
	cout << "bigger one is : " << get_max('a', 'b') << endl;

	return 0;
}

 

 

typename을 여러개 사용할 수도 있다.

template<typename T1, typename T2>
T2 doSomething(T1 a, T2 b) {
	T1 temp_a = a * (T1)10;
	T2 temp_b = b * (T2)20;

	cout << temp_a << endl;
	cout << temp_b << endl;

	return T2;
}

 

 

 

Class template

 

클래스에서도 사용이 가능하다.

#include <iostream>

using namespace std;

template<typename T>

class MyData {
public:
	T data;
	MyData(T _data) : data(_data) { };
};


int main() {

	MyData<int> a(10);
	MyData<double> b(20.3);
	MyData<char> c('z');

	return 0;
}

 

 

Comments