개념

  • 실행시간이 아닌 컴파일 시간에 연산을 수행하는 코드.
  • 재귀의 종료를 위해 template specialization을 사용.
  • C++11 이전에는 이런 방식으로 메타 프로그래밍.
  • **Modern C++**에서는 constexpr 사용.

활용 예시 1: Factorial 계산 (Template Meta Programming)

  #include <iostream>

// Template Meta Programming
template<std::size_t N>
struct Factorial {
    enum { value = N * Factorial<N-1>::value };
};

// 재귀 종료를 위한 Specialization
template<>
struct Factorial<1> {
    enum { value = 1 };
};

int main() {
    int ret = Factorial<5>::value;  // 120
    std::cout << ret << std::endl;
}
  
  • 컴파일 시간에 팩토리얼이 계산됨.
  • 재귀적 템플릿 인스턴스화를 통해 값이 결정.

활용 예시 2: Factorial 계산 (constexpr)

  constexpr std::size_t factorial(std::size_t n) {
    return n == 1 ? 1 : n * factorial(n-1);
}

int main() {
    constexpr std::size_t ret = factorial(5);  // 120
    std::cout << ret << std::endl;
}
  
  • C++11 이후: constexpr로 컴파일 시간 계산.
  • 가독성 좋고 함수형 스타일.

Variable Template

  • 변수에도 템플릿을 적용하는 기능.
  • 특정 타입에 따라 다른 상수를 제공할 때 사용.

활용 예시 1: 제작 연도 제공

  #include <iostream>

// 기본값: -1
template<typename>
inline constexpr int made_year = -1;

class AAA {};
class BBB {};

// Specialization

// AAA 타입
template<>
inline constexpr int made_year<AAA> = 2020;

// BBB 타입
template<>
inline constexpr int made_year<BBB> = 2022;

int main() {
    std::cout << made_year<AAA> << std::endl;  // 2020
    std::cout << made_year<BBB> << std::endl;  // 2022
}
  

실활용 예시: borrowed_range

  • C++20에서 소개된 개념.
  • 자원을 소유하지 않고 **다른 range (container)**가 소유한 자원을 사용하는 range.
  • string_view와 비슷한 역할.
  • std::ranges::enable_borrowed_range 같은 variable template으로 특성 확인.
  // C++20 <ranges>

// 기본값은 false
template<typename>
inline constexpr bool enable_borrowed_range = false;

// string_view는 true
#include <string_view>
template<typename T, typename Traits>
inline constexpr bool enable_borrowed_range<std::basic_string_view<T, Traits>> = true;
  
  • 특정 타입 (string_view)에 대해 borrowed_range 여부를 컴파일 시간에 확인.