2015년 10월 15일 목요일

[C++] specialization




#include 
using namespace std;

//1) 기본 템플릿
//primary template(주 템플릿)
template class Stack
{
 T buff[10];
public:
 void push() {cout << "push(T)" << endl;}
};

//2) 부분적인 타입에 특화된 템플릿을 사용하고 싶다면?
//partial specialization(부분 전문화)
template class Stack
{
 T buff[10];
public:
 void push() {cout << "push(T*)" << endl;}
};

//3) 특정 타입에 특화된 템플릿을 사용하고 싶다면?
//specialization(전문화)
template<> class Stack  //를 삭제한다.
{
 char* buff[10];   //T를 특정 타입으로 변경한다.
public:
 void push() {cout << "push(char*)" << endl;}
};

void main()
{
 Stack s1;
 s1.push();  //T
 Stack s2;         //c++에서는 포인터도 타입으로 인지한다.
 s2.push();  //T*
 Stack s3;
 s3.push();  //char*
}

정리 :
모든 타입에 대해서 처리할 수 있는 템플릿을 primary template이라 하고
부분 타입에 대해서 처리할 수 있는 템플릿을 partial specialization 이라 한다.
특정 타입에 대해서 처리할 수 있는 템플릿을 specialization 이라 한다.

왜 필요한가??(template meta programming 의 장점)

예를 들어, 5!(factorial)의 값을 얻으려 할 때,
loop 혹은 recursive code는 run time 에 동작한다.
하지만 class template과 function template 은 compile time에 동작하고
따라서 partial specialization과 specialization 을 이용하면 runtime이 아닌 compile time에 작업을 처리할 수 있다.

댓글 없음:

댓글 쓰기

[C++] meta programing

재귀 호출에 관해 template meta programming 을 적용한 예제를 살펴보자. #include using namespace std; int fact(int n){ if(n factorial 연산을 하는 일반적인 재귀 호출 함...