GSI

책을 2, 3번 정도 읽으니 조금 이해가 되네요.
아직 100%는 아니지만 ^^

처음에는 템플릿으로 참 알아 보지도 못하는 것을 구현하기에.. 난해 했지만.

지금 조금 이해가 되는 부분에서 느껴 지는 것은
템플릿을 사용해서 컴파일 타임에서 오류를 잡아 주거나,
메모리 생성하는 규칙을 템플릿으로 typedef 잡아서 사용하거나 하는 부분들이
잘만 활용하면 상속 만큼이나 아니면 더 많은 부분을 효과적으로 구현하게
해주는 것인지도 모르겠다.

아래의 예를 잠깐 보면..

// TemplateTest.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"

template <class T>
struct OpNewCreator
{
 static T* Create()
 {
  printf("OpNewCreator - new 사용\n");
  return new T;
 }
};

template <class T>
struct MallocCreator
{
 static T* Create()
 {
  printf("MallocCreator - malloc 사용\n");
  void* buf = std::malloc(sizeof(T));
  if(!buf) return 0;
  return new(buf) T;
 }
};

class Widget
{
public:
 Widget() { printf("Widget 생성자 호출\n"); }
 ~Widget();
};

class CTest : public Widget
{
public:
 CTest() { printf("Widget 생성자 호출\n"); }
 ~CTest() {}
};

template < template <class Created> class CreationPolicy >
class WidgetManager : public CreationPolicy< Widget >
{
public:
 WidgetManager()
 {
  Dosomething();
 }

 ~WidgetManager() {}

 void Dosomething()
 {
  CTest* pw = CreationPolicy<CTest>().Create();
 }
};

typedef WidgetManager< OpNewCreator > MyWidgetMgr_New;
typedef WidgetManager< MallocCreator > MyWidgetMgr_Malloc;


int _tmain(int argc, _TCHAR* argv[])
{
 MyWidgetMgr_New a;
 MyWidgetMgr_Malloc b;

 return 0;
}

어쩌면.. 위의 typedef 부분인거 같다.
내가 new를 사용해서 객체를 할당 한다거나 하다가 상황에 따라서 malloc를 사용해야 한다고 하면
코드를 고치기 보다 typedef 부분을 수정해 주므로 모든게 해결이 된다.

아래는 실행된 모습이다.

사용자 삽입 이미지


하지만 여기서 궁금한건...
Widget를 Class 부분에서 미리 정의 해 주는 부분인데.. 잘 이해가 되지 않는다.
Posted by gsi
: