* pow

 

template<int m, int n>
struct MyPow
{
    static const long long result = m * MyPow<m, n - 1>::result;
};

template<int m>
struct MyPow<m, 0>
{
    static const long long result = 1;
};

 

 

* factorial

 

template<int n>
struct MyFactorial
{
	static const long long result = n * MyFactorial<n - 1>::result;
};

template <>
struct MyFactorial<1>
{
	static const long long result = 1;
};

 

 

* enable_if

 

template <bool condition, typename T = void>
struct MyEnableIf {}; // condition이 false일때는 정의되지 않는다.

template <typename T> // condition이 true일때만 타입을 정의한다.
struct MyEnableIf<true, T> { using type = T; }; 

template <typename T>
typename MyEnableIf<std::is_integral<std::remove_reference_t<T>>::value, bool>::type
                Multiply(T&& a, T&& b) { return a * b; }

 

 

 

* is_prime

 

// 나눠 떨어지면 재귀를 빠져나가도록 설계한다.
template <int n, int d>
struct Divisible
{
    static const bool result = (0 == n % d) ? true : Divisible< n, d - 1 >::result;
};

// 2에서 브래이크를 걸어준다.
template <int n>
struct Divisible <n, 2>
{
    static const bool result = (0 == n % 2);
}; 


template <int n>
struct MyIsPrime 
{
    static const bool result = (false == Divisible< n, n / 2 >::result);
};

template <>
struct MyIsPrime<2> // 2는 소수, n / 2 부터 나눠서 확인하기 때문에 예외처리
{
    static const bool result = true;
};

template <>
struct MyIsPrime<3> // 3은 소수, n / 2 부터 나눠서 확인하기 때문에 예외처리
{
    static const bool result = true;
};

 

'C++' 카테고리의 다른 글

템플릿 메타 프로그래밍(Template Meta Programming, TMP)  (0) 2022.05.23
가변인자 템플릿(Variadic Template) 예시  (0) 2022.05.23
가변인자 템플릿(Variadic Template)  (0) 2022.05.23
템플릿(Template)  (0) 2022.05.23
람다(Lambda)  (0) 2022.04.11

+ Recent posts