당신은 많은 수를 계산하기 위해 여러 정밀 수학을 사용할 수 있습니다 (전 3 템플릿 매개 변수를 사용하여 96 비트 연산을 사용하여 아래의 내 예를 들어, 당신은 어떤 상수를 사용할 수 있습니다). 템플릿 매개 변수로 둘 이상의 정수가 있어야합니다.
컴파일 타임 곱셈을 수행 할 때 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에 대한 지원을 훨씬 더 간단하고 아름답게 처리하며 동일한 작업을 수행합니다. –