[C++STL] 템플릿 - 클래스 템플릿

박남호·2022년 12월 5일
0

클래스 템플릿은 함수 템플릿에서 클래스로 바뀐 것뿐 별반 다르지 않다. 아래는 자료형만 int, double, string으로 다르고 클래스의 함수는 Print로 같다.

#include <iostream>
#include <string>
using namespace std;

class IntPrint
{
	int tInt = 123;
public:
	void Print() { cout << "Int 출력 : %d" << tInt; };
};
class DoublePrint
{
	double tDouble = 123.45;
public:
	void Print() { cout << "Int 출력 : %d" << tDouble; };
};

class StringPrint
{
	string tString = "12345";
public:
	void Print() { cout << "Int 출력 : " << tString; };
};

int main()
{	
	IntPrint tIntPrint;
	DoublePrint tDoublePrint;
	StringPrint tStringPrint;
	tIntPrint.Print();
	tDoublePrint.Print();
	tStringPrint.Print();
	return 0;
}

위와 같은 경우도 클래스 템플릿을 사용하면 매우 간단하게 코드를 작성할 수 있다. 클래스 템플릿은 클래스 앞에 template< t > 키워드를 붙이면 된다. 클래스 템플릿 형식은 template class Test이다. 이전 예제에 클래스 템플릿을 적용하여 아래의 예제를 작성했다.

#include <iostream>
#include <string>
using namespace std;

template <typename T>
class TestPrint
{
public:
	void Print(T t) { cout << "출력 : " << t << endl; };
};

int main()
{	
	TestPrint<int> tIntPrint;
	tIntPrint.Print(123);
	TestPrint<double> tDoublePrint;
	tDoublePrint.Print(123.45);
	TestPrint<string> tStringPrint;
	tStringPrint.Print("123456789");
	return 0;
}

클래스 템플릿을 선언하기 전에 TestPrint와 같이 데이터 타입을 명시해준다. 템플릿의 매개변수도 함수의 매개변수처럼 디폴트 매개변수 값을 지정할 수 있다. 아래는 디폴트 매개변수 값을 지정한 예제이다.

#include <iostream>
#include <string>
using namespace std;

template <typename T = int>
class TestPrint
{
public:
	void Print(T t) { cout << "출력 : " << t << endl; };
};

int main()
{	
	TestPrint<> tIntPrint;
	tIntPrint.Print(123);
}

위 예제와 같이 디폴트로 자료형을 지정하면 나중에 클래스 템플릿 객체를 생성할 때 데이터 타입을 명시하지 않을 수 있다. TestPrint<>는 TestPrint< int >와 같이 동작한다.

profile
NamoPark

0개의 댓글