据说模板编程是从计算素数开始的。所以编译器肯定可以在编译时计算出来。甚至我也能以某种方式编写或重写这样的模板:
template<unsigned p, unsigned d>
struct DoIsPrime {
static constexpr bool value = (p%d != 0) && DoIsPrime<p,d-1>::value;
};
template<unsigned p>
struct DoIsPrime<p, 2> {
static constexpr bool value = (p % 2 != 0);
};
template<unsigned p>
struct IsPrime {
static constexpr bool value = DoIsPrime < p, p / 2 >::value;
};
template<>
struct IsPrime<0> {
static constexpr bool value = false;
};
template<>
struct IsPrime<1> {
static constexpr bool value = false;
};
template<>
struct IsPrime<2> {
static constexpr bool value = true;
};
template<>
struct IsPrime<3> {
static constexpr bool value = true;
};
template<unsigned p>
bool isPrime = IsPrime<p>::value;
你还怎么救他们?现在如何在编译时编写素数表?比方说得到
unsigned int p[] = { }
p[i]
直到某个边界的素数在哪里?p[0]=2
,p[1]=3
等等?
选项1
我们得到一个在给定整数之前遇到的素数数组。
在线编译器:
选项 2
我们得到一个给定长度的素数数组。
在线编译器
我将在我的回答中使用您的工作:
屏幕上会有 10 个素数。
现在这里发生了什么。递归实例化并继承 PrimeAray 模板。在每一步中,我们将要检查的数字加 1。如果该数字是素数,则将其添加到列表中并将给定数字减 1。当数字变为 0 时,则已找到所有必要的素数,并且您可以将结果放入数组并中断递归。
完整示例