[C++] 템플릿 메타 프로그래밍

muchan
muchan
∙∙조회 5

https://modoocode.com/221

https://modoocode.com/222

위의 사이트에서 공부한 내용을 정리..

하고 싶었지만 내용이 정말 어려워서 대충 이해한 느낌만 적어보겠습니다


템플릿 메타 프로그래밍(TMP)

C++의 템플릿을 이용하여 컴파일 타임에 연산을 수행하거나 새로운 타입을 생성하는 프로그래밍 기법이다

arduino
#include <iostream>

template <int N>
struct INT {
  static const int num = N;
};

template <typename a, typename b>
struct add {
  typedef INT<a::num + b::num> result;
};

template <typename a, typename b>
struct divide {
  typedef INT<a::num / b::num> result;
};

using one = INT<1>;
using two = INT<2>;
using three = INT<3>;

template <typename N, typename d>
struct check_div {
  // result 중에서 한 개라도 true 면 전체가 true
  static const bool result = (N::num % d::num == 0) ||
                             check_div<N, typename add<d, one>::result>::result;
};

template <typename N>
struct _is_prime {
  static const bool result = !check_div<N, two>::result;
};

template <>
struct _is_prime<two> {
  static const bool result = true;
};

template <>
struct _is_prime<three> {
  static const bool result = true;
};

template <typename N>
struct check_div<N, typename divide<N, two>::result> {
  static const bool result = (N::num % (N::num / 2) == 0);
};

template <int N>
struct is_prime {
  static const bool result = _is_prime<INT<N>>::result;
};

int main() {
  std::cout << std::boolalpha;
  std::cout << "Is 2 prime ? :: " << is_prime<2>::result << std::endl;
  std::cout << "Is 10 prime ? :: " << is_prime<10>::result << std::endl;
  std::cout << "Is 11 prime ? :: " << is_prime<11>::result << std::endl;
  std::cout << "Is 61 prime ? :: " << is_prime<61>::result << std::endl;
}

대충 이런 코드인데

컴파일 타임에 바로 연산을 할 수 있다

왜 쓰는가

단위 연산을 할 때 주로 쓰인다고 한다

예를 들어 3cm 와 5m가 있을 때 3*5는 컴파일 타임에 정상적으로 결과가 나오지만

실제로는 단위가 맞지 않는다

이런걸 막기 위해 템플릿 메타 프로그래밍을 사용한다고 한다


너무 어렵기도 하고 솔직히 잘 안쓸 것 같아서 대충 느낌만 보고 넘기려고 합니다.. ㅎ

나중에 자주 쓸 것 같으면 그때 다시 공부해보겠습니다.