Search code examples
c++template-meta-programminggreatest-common-divisor

Using template metaprogramming in C++, find the GCD of two integers


I want to know a template meta-programming solution to the problem of finding the GCD of two numbers using using the recursive Euclid's Algorithm, given below for your reference.

function gcd(a, b)
    if b = 0
       return a; 
    else
       return gcd(b, a mod b);

Any help would be highly appreciated!


Solution

  • something like this?

    #include <utility>
    #include <iostream>
    
    template<int a, int b> struct gcd
    {
        static constexpr auto value = gcd<b, a % b>::value;
    };
    
    template<int a>
    struct gcd<a, 0>
    {
        static constexpr auto value = a;
    };
    
    int main()
    {
        auto x = gcd<10,5>::value;
    
        std::cout << x << std::endl;
    }