您可以使用多精度數學的方法計算大量的(在我的例子下面我用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