'2009/04/11'에 해당되는 글 1건

  1. 2009/04/11 템플릿 클래스와 멤버함수 깔끔하게 작성하기

템플릿 클래스와 멤버함수 깔끔하게 작성하기

|
자주 쓰지는 않지만 기존 작성된 템플릿 클래스를 Wrapping 하다보면 (특히 리스트!) 템플릿 클래스를 사용해야 하는 경우가 많습니다.

하지만 이것 저것 작성하다 보면 템플릿 클래스의 헤더가 복잡해지는 경우가 많은데요.

이는 템플릿 클래스(Template Class)의 멤버함수는 헤더에 정의해야만 하기 떄문입니다
. MFC나 STL에서 디버깅을 하다가 만나는 템플릿 클래스의 헤더들을 보면 구현부가 노출되어 있죠.
(Cpp 파일에 따로 멤버 함수를 정의하면 VC는 링크 오류를 발생시킵니다. <아마도 LNK2014 일 듯 합니다.> export 키워드로 명시적으로 표현할 수 있지만 VC 컴파일러는 이를 인식하지 못합니다.)

한두줄로 구현되는 함수들이야 헤더에 넣어도 문제없겠지만 복잡한 구현부를 가진 함수나, 다수의 함수를 구현하는 경우에는 헤더가 지저분해지기 쉽상입니다.

그래서 많은 분들이 쓰시는 방법은 인라인 함수(inline function) 인데요.
다음과 같이 구현하면 선언부와 구현부를 분리할 수 있어 가독성이 상당히 좋고 헤더도 깔끔해져서 이런 방법으로 구현하곤 합니다.

(1) 기존방법 :

MyTemplateClass.h

template<class T, int size>
class MyTemplateClass
{
public :
MyTemplateClass() { miTotalCount = 0; };
~MyTemplateClass() {};

void Set (T oItem, int index) { moArray[index] = oItem;};
T Get(int index) { return moArray[index]; }
private :
int  miTotalCount;
T   moArray[size];
}

 
(2) 인라인 함수 사용방법 :

MyTemplateClass.h

template<class T, int size>
class MyTemplateClass
{
public :
MyTemplateClass() {};
~MyTemplateClass() {};

void Set (T oItem, int index) {};
T Get(int index) {}
private :
int  miTotalCount;
T   moArray[size];
}

#include " MyTemplateClass.inl"


---------------------------------------------------------------------

MyTemplateClass.inl


template<class T, int size>
inline MyTemplateClass<T, size>::MyTemplateClass()
{
miTotalCount = 0;
}

template<class T, int size>
inline void MyTemplateClass<T, size>::~MyTemplateClass()
{
}

template<class T, int size>
inline void MyTemplateClass<T, size>::Set(T oItem, int index)
{
moArray[index] = oItem;
}

template<class T, int size>
inline T MyTemplateClass<T, size>::Get()
{
return moArray[index];
}

 
이렇게 헤더에서 인라인 구현함수 파일(MyTemplateClass.inl)을 포함(include)하게 되면 정의파일과 구현파일로 따로 분리할 수도 있습니다.

함수가 간단해서 후자의 방법이 더 복잡해 보이지만 복잡한 클래스의 경우 이렇게 작성하면 헤더도 간소해지고 가독성도 높아지리라 생각합니다.

* 컴파일을 안돌려봐서 잘 돌아갈지 모르겠네요 ^^;



저작자 표시 비영리 변경 금지
Trackback 0 And Comment 0
prev | 1 | next