GCD Via C++ Template Metaprogramming

Via IRC:


    09:06 < jepler> michael: c++ template metaprogramming puzzle
    09:06 < jepler> I want a template class gcd<a,b> so that
        gcd<a,b>::value == gcd(a,b)
    09:07 < jepler> actually I bet it's pretty simple

It turns out Jeff's right; it's pretty simple.

#include <iostream>

template<int A, int B>
struct GCD { enum { value = GCD<B,A%B>::value }; };

template<int A> struct GCD<A,0> { enum { value = A }; };

int main() {
std::cout << GCD<N1,N2>::value << "\n";
return 0;
}

To run it, you compile it, defining N1 and N2 on the command line, and run the resulting program, which prints the result of the calculation GCD(N1,N2), which was performed at compile time. Neat!

~$ g++ -DN1=293888 -DN2=4837888 gcd.cc && ./a.out
512
~$

Sun, 20 Jul 2008 12:59

Comments: 0

Reader Comments

Add a Comment

  • Only the name field is mandatory. It's hard to keep track of a conversations where everyone is Anonymous.
  • If you choose to leave an email address, it will not be shown on the page.
  • A limited subset of HTML is allowed in your comment.

Name

Email

URL


Comment: (Limited HTML allowed.)