#include <iostream>
template <unsigned int p, unsigned int i=2, bool= (i*i>p) > struct IsPrime
{
enum{Result = (p%i)&&(IsPrime<p, i+1>::Result)};
};
template<unsigned int p, unsigned int i> struct IsPrime<p,i,true>
{
enum{Result=p};
};
template<unsigned int p, bool = IsPrime<p>::Result > struct MaxPrime
{
enum{Result = MaxPrime<p-1>::Result};
};
template<unsigned int p> struct MaxPrime<p, true>
{
enum{Result=p};
};
void main()
{
std::cout << MaxPrime<129>::Result << std::endl;
}
再来一个,求100以内的所有素数:
template <unsigned int p, unsigned int i=2, bool= (i*i>p) > struct IsPrime
{
enum{Result = (p==2)|| (p%i)&&(IsPrime<p, i+1>::Result)};
};
template<unsigned int p, unsigned int i> struct IsPrime<p,i,true>
{
enum{Result=p};
};
template<unsigned int p> struct aux;
template<> struct aux<0>{}; //只针对p==0时有定义,p!=0时无定义!
template<unsigned int p> struct PrintPrime
{
aux<IsPrime<p>::Result> obj; /*当IsPrime<p>::Result==1时,编译器会 提示使用没定义的结构aux<p> with p=97,
with p = 91, with p=89....with p=1;
而97,91,89,...,1正是我们所求的100 以内的素数.*/
PrintPrime<p-1> next;
};
template<> struct PrintPrime<0>{};
PrintPrime<100> obj;
//只需编译以上代码,不需要link,不需要main函数,不需要运行,即可得出答案.实现零运行时期求解!