I use compile-time int powers calculation Power, to compute n**p. It uses ints. I want to calculate something that's bigger than int, ok ? It fits into u64 (unsigned long long). Can C++ templates do compile-time calculations on u64 ? Enums cannot do this. On doubles ? Possible ?
I would really want the type to be arg of the template. Is it possible ? My compiler is not c++0x.
Thanks Andrei
template<int N, int P> struct Power {
enum { val = N * Power<N, P-1>::val };
};
template<int N> struct Power<N, 0> {
enum { val = 1 };
};
int result = Power<2, 5>; // 2**5 == 32
Yes, you can do compile-time computations on any primitive integral type. You cannot, however, do computations on floating-point values because templates can't be parameterized over those values. The upcoming C++0x standard will introduce special classes to do compile-time rational arithmetic, so you may be able to use that if you wish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With