/* I've witten the following code example after while reading the great book * "C++ Templates - The Complete Guide" * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002 * * In this book an example for calculating primes is given, which outputs * the results as compiler-error-messages. This is an example I've written * to get the primes as program output instead of error messages. * My example is not bullet proof, anyway it was just for fun. :) * * (C) Copyright Andre Alexander Bell 2003. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include #include // the following three IfThenElse Templates are taken from // "C++ Templates - The Complete Guide" template struct IfThenElse; template struct IfThenElse { typedef THEN result_type; }; template struct IfThenElse { typedef ELSE result_type; }; // This is an adaption of the Value template shown in Chapter 17 of // "C++ Templates - The Complete Guide" template struct Value { enum { result = b }; }; // This is where the work ist done :) template struct IsPrime { // if (below sqrt(N) and N is not divisible by I) // typedef IsPrime SubT; // else // typedef Value SubT; // This one will give SubT::result==true typedef typename IfThenElse< (I*I, Value >::result_type SubT; enum { result = (N==2) || ((N%I)!=0) && (SubT::result) }; }; // Ok, here we go, let's see if these are primes int main() { // Set boolalpha to get bools printed as 'true' and 'false' std::cout.setf(std::ios_base::boolalpha); // static_cast makes result be a bool for output std::cout << "IsPrime<2>::result = " << static_cast(IsPrime<2>::result) << std::endl; std::cout << "IsPrime<5>::result = " << static_cast(IsPrime<5>::result) << std::endl; std::cout << "IsPrime<23>::result = " << static_cast(IsPrime<23>::result) << std::endl; // The following number is prime. To get this compiled you will need a template recursion // depth > 1000. With g++ try this: // // g++ -ftemplate-depth-1001 -o isprime isprime.cpp // // std::cout << "IsPrime<1000003>::result = " << static_cast(IsPrime<1000003>::result) << std::endl; return 0; }