앞서 Chapter 11에서 우리는 다음의 클래스들을 정의한바 있다.
템플릿을 사용하여 해결할 수 있다.
template <typename T>
class Point
{
private:
T xpos, ypos;
public:
Point(T x=0, T y=0) : xpos(x), ypos(y){}
void Show Poisition() const
...
}
함수 템플릿과 마찬가지로, 컴파일러는 ‘클래스 템플릿’을 기반으로 ‘템플릿 클래스’를 만들어낸다.
템플릿 클래스의 객체를 생성할 때는 자료형 정보를 생략할 수 없다.
Point <int> pos1(1, 2);
Point <double> pos2(1.1, 2.2);
Point <char> pos3('p', 'f');
클레스 템플릿도 멤버함수를 클래스 외부에 정의하는 것이 가능하다. 예를 들어서 다음과 같이 정의된 클래스 템플릿이 있다면,
template <typename T>
class SimpleTemplate
{
public:
T SimpleFunc(const T& ref);
}
template <typename T>
T SimpleTemlpate<T>::SImpleFunc(const T& ref)
{
}
위의 함수정의에서 SimpleTemplate<T> 가 의마하는 바는 다음과 같다.
“T에 대해 템플릿화 된 SimpleTemplate 클래스 템플릿”
일반적인 클래스와 같이 선언과 정의를 분리하다 보면 main 문에서 에러가 날 수 있다.
int main(void)
{
Point<int> pos1(3, 4); // Point<int> 템플릿 클래스 만들어지는 시점 → 헤더파일 참고 불가.
Point<double> pos2(2.4, 3.6);
Point <char> pos3(’P’, ‘F’);
}
해결방법은 헤더파일에 정의를 넣거나 or .cpp 파일을 main.cpp 파일에 추가하는것이다.