반응형

템플릿 메타 프로그래밍

  • 컴파일 시간에 연산을 수행하는 개념
  • 템플릿 파라미터 5를 받았을때 5 * 4 * 3 * 2 * 1 값을 반환하는 Factorial 구현
#include <iostream>
#include <type_traits>
using namespace std;

//  템플릿 메타 프로그래밍(template meta programming)
template<int N> struct Factorial
{
    enum { value = N * Factorial<N-1>::value };
};

// 재귀의 종료를 위해 특수화(Specialization)
template<> struct Factorial<1>
{
    enum { value = 1 };
};

int main()
{

    int n = Factorial<5>::value; // 5 * 4 * 3 * 2 * 1 => 120
    // 5 * Factorial<4>::value
    // 4 * Factorial<3>::value
    // 3 * Factorial<2>::value
    // 2 * Factorial<1>::value
    // 1

    cout << n << endl;
}

 

C++11 이후 부터는 enum대신 constexpr을 사용할 수 있다.

#include <iostream>
#include <type_traits>
using namespace std;

//  템플릿 메타 프로그래밍(template meta programming)
template<int N> struct Factorial
{
    //enum { value = N * Factorial<N-1>::value };
    static constexpr int value = N * Factorial<N - 1>::value;
};

// 재귀의 종료를 위해 특수화(Specialization)
template<> struct Factorial<1>
{
    //enum { value = 1 };
    static constexpr int value = 1;
};

int main()
{

    int n = Factorial<5>::value; // 5 * 4 * 3 * 2 * 1 => 120
    // 5 * Factorial<4>::value
    // 4 * Factorial<3>::value
    // 3 * Factorial<2>::value
    // 2 * Factorial<1>::value
    // 1

    cout << n << endl;
}
반응형

+ Recent posts