这玩意不实用,因为它受限于编译器的递归解析能力。。。在VS2010上能计算到499,再高就直接报错了。。。而且编译时间也是十分感人的
// ConsoleApp1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
template <int p, int i>
class is_prime
{
public:
enum {
prim = (p == 2) || (p % i) && is_prime<(i> 2 ? p : 0), i - 1>::prim
};
};
template<>
class is_prime<0, 0>
{
public:
enum { prim = 1 };
};
template<>
class is_prime<0, 1>
{
public:
enum { prim = 1 };
};
template <int i>
class Prime_print
{
public:
Prime_print a;
enum { prim = is_prime<i, 1 i ->::prim };
void f() {
a.f();
if (prim) cout << i << endl;
}
};
template<>
class Prime_print<1>
{
public:
enum { prim = 0 };
void f() {
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Prime_print<20> a;
a.f();
return 0;
}
</20></1></i,></int></0,></0,></(i></int></iostream>