2015년 10월 15일 목요일

[C++] meta programing


재귀 호출에 관해 template meta programming 을 적용한 예제를 살펴보자.


#include 
using namespace std;

int fact(int n){
 if(n <= 1)
  return 1;
 return n * fact(n-1);
}

void main()
{
 cout << fact(5) << endl;
}
factorial 연산을 하는 일반적인 재귀 호출 함수 fact이다.
fact function 을 template 으로 변경해보자.


#include 
using namespace std;

//fact function 을 template 으로 변경
template struct Fact  
{
 enum{ value = N * Fact::value};  //컴파일 타임에 value가 생성, 저장됨
       //Fact 내부의 value에 접근하려면, :: 접근지정 연산자를 사용해야 함에 주의
};

//전문화(specialization)이용하여 종료 조건 
template<> struct Fact<1>
{
 enum { value = 1 };
};

void main()
{
 cout << Fact<5>::value << endl;
 // 5 * Fact<4>::value
 // 5 * 4 * Fact<3>::value
 // 5 * 4 * 3 * Fact<2>::value
 // 5 * 4 * 3 * 2 * Fact<1>::value
}

종료 조건 N이 1인경우를 specialization 을 이용하면 된다.
결과적으로 컴파일 타임에 Fact<5>::value 가 120 으로 바뀌게 되어 성능 향상을 가져온다.

하지만 이 기법은 아직 학문적 용도로만 쓰이며, 사용할 수 있는 경우가 제한적이기 때문에 널리 쓰이진 않는다.

댓글 없음:

댓글 쓰기

[C++] meta programing

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