Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile time templated C++ calculations on unsigned long long ? on doubles?

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
like image 541
Andrei Avatar asked Dec 02 '25 08:12

Andrei


1 Answers

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.

like image 87
templatetypedef Avatar answered Dec 04 '25 00:12

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!