본문 바로가기
기타 정리

boost의 static_gcd / static_lcm 흉내내기

by 날쑤 2015. 10. 28.

Intro

  TMP로 유클리드 호제법을 구현해서 최대공약수와 최소공배수를 컴파일 타임에 얻어보자.

#include <iostream>

using namespace std;

template <size_t A, size_t B>
struct StaticGreatestCommonDivisor 
{
    enum { kValue = StaticGreatestCommonDivisor<B, A % B>::kValue };
};

template <size_t A>
struct StaticGreatestCommonDivisor<A, 0> 
{
    enum { kValue = A };
};

template <size_t A, size_t B>
struct StaticLeastCommonMultiplier
{
private:
    static const size_t kGCD = StaticGreatestCommonDivisor<A,B>::kValue;
    static const size_t kA = A/kGCD;
    static const size_t kB = B/kGCD;

public:
    enum { kValue = kA * kB * kGCD };
};


int main(int argc, char* argv[])
{
    const size_t kValue = StaticLeastCommonMultiplier<10, 18>::kValue;
    char array[kValue]{0};
    
    cout << sizeof(array) << endl;

    return 0;
}

'기타 정리' 카테고리의 다른 글

CallStack을 찍어보자.  (3) 2015.08.07