您可以使用多精度数学的方法计算大量的(在我的例子下面我用96位的计算与3模板参数,你可以使用任何常数)。您需要有多个整数作为模板参数。
在执行编译时乘法时,应该乘以具有64位结果的32位数;结果应该分成2个模板参数。
溢出检查可能是可能的,但可能会非常棘手。
const uint64_t W = 1000000000; // word size: 2^32 is best; any smaller number is OK
// I use a power of 10 as word size for ease of printing (see main() below)
// The following class performs multiplication of (n0 + W*n1 + W*W*n2) by (base)
template <unsigned n0, unsigned n1, unsigned n2, uint64_t base, unsigned p> class power_temp
{
typedef power_temp<
n0 * base % W,
n1 * base % W + n0 * base/W,
n2 * base % W + n1 * base/W,
base, p - 1> mult_type;
public:
static const unsigned x0 = mult_type::x0;
static const unsigned x1 = mult_type::x1;
static const unsigned x2 = mult_type::x2;
};
// The following partial specialization is used to end recursion
template <unsigned n0, unsigned n1, unsigned n2, uint64_t base>
class power_temp<n0, n1, n2, base, 0>
{
public:
static const unsigned x0 = n0;
static const unsigned x1 = n1;
static const unsigned x2 = n2;
};
// The following class calculates a power, using compile-time calculations
template <unsigned base, unsigned p> struct power
{
static const unsigned x0 = power_temp<1, 0, 0, base, p>::x0;
static const unsigned x1 = power_temp<1, 0, 0, base, p>::x1;
static const unsigned x2 = power_temp<1, 0, 0, base, p>::x2;
};
int main()
{
typedef power<123456789, 3> my1;
printf("%09d%09d%09d\n", my1::x2, my1::x1, my1::x0);
typedef power<5, 33> my2;
printf("%09d%09d%09d\n", my2::x2, my2::x1, my2::x0);
}
对于那些在今年阅读+ + C + + 11和更新版本支持constexpr,它是一个更简单,更美丽,做同样的工作。 – 2013-04-21 21:00:57