heron

서론

C++을 공부하다 보면, 필연적으로 TMP를 마주하게 된다. 아마도 추측컨데, 대부분의 학생은 이 개념에서 일종의 아름다움을 느낄 것이다. 나도 그랬다.

그리하여 대학교 동아리에서, TMP가 무엇인지 소개하는 발표를 준비했다.

소스코드와 발표자료를 게시하겠다.

본론

발표자료

TMP_presentation.pdf (자유롭게 수정 및 사용 가능합니다.)
TMP_presentation-01.png TMP_presentation-02.png TMP_presentation-03.png TMP_presentation-04.png TMP_presentation-05.png TMP_presentation-06.png TMP_presentation-07.png TMP_presentation-08.png TMP_presentation-09.png TMP_presentation-10.png TMP_presentation-11.png TMP_presentation-12.png TMP_presentation-13.png TMP_presentation-14.png TMP_presentation-15.png TMP_presentation-16.png TMP_presentation-17.png

Compile Time Iteration

#include <iostream>

template
struct PrintNumbers {
    static void print() {
        PrintNumbers::print();
        std::cout << N << std::endl;
    }
};

template<>
struct PrintNumbers<1> {
    static void print() {
        std::cout << 1 << std::endl;
    }
};

int main() {
    PrintNumbers<10>::print();
    return 0;
}

Compile Time Factorial

#include <iostream>

#define input_n 50
// #define input_n 10

template
struct Factorial {
    static const int value = N * Factorial::value;
};

template<>
struct Factorial<0> {
    static const int value = 1;
};

constexpr int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; ++i) {
        result *= i;
    }
    return result;
}

int main() {
    std::cout << "Factorial("<< input_n << "): " << Factorial::value << std::endl;

    int x = 10;
    std::cout << "Factorial("<< x << "): " << factorial(x) << std::endl;
    return 0;
}

Compile Time Iteration

#include <iostream>
#include <ctime>

#define input_n 42

template
struct Fibonacci {
    static const int value = Fibonacci::value + Fibonacci::value;
};

template<>
struct Fibonacci<0> {
    static const int value = 0;
};

template<>
struct Fibonacci<1> {
    static const int value = 1;
};

int Fibonacci_recursive(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    return Fibonacci_recursive(n-1) + Fibonacci_recursive(n-2);
}

int main() {
    clock_t start = clock();
    std::cout << "Fibonacci("<< input_n << "): " << Fibonacci::value << std::endl;
    clock_t end = clock();
    std::cout << "Compile time Fibonacci: " << (double)(end - start) / CLOCKS_PER_SEC << "s" << std::endl;

    start = clock();
    std::cout << "Fibonacci("<< input_n << "): " << Fibonacci_recursive(input_n) << std::endl;
    end = clock();
    std::cout << "Run time Fibonacci: " << (double)(end - start) / CLOCKS_PER_SEC << "s" << std::endl;
    return 0;
}