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
~$
Comments: 0