Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Sign of an integer
- template<bool b> struct SIGN {static const int value = ( b * 2 ) - 1; };
- // Positive powers of two (fast exponentiation)
- template<unsigned int N> struct POW2_POS {
- static const float value =
- POW2_POS<N%2>::value
- * POW2_POS<N/2>::value
- * POW2_POS<N/2>::value;
- };
- template<> struct POW2_POS <1> { static const float value = 2.0f; };
- template<> struct POW2_POS <0> { static const float value = 1.0f; };
- // Negative powers of two
- template<unsigned int N> struct POW2_NEG {static const float value = 1.0f / POW2_POS<N>::value; };
- // Calls POW2_POS or POW2_NEG depending on boolean parameter
- template<bool b, int N> struct POW2_SIGNED;
- template<int N> struct POW2_SIGNED<true, N> { static const float value = POW2_POS<N>::value;};
- template<int N> struct POW2_SIGNED<false, N> { static const float value = POW2_NEG<N>::value;};
- // Integer power of two
- template<int N> struct POW2 {
- static const float value = POW2_SIGNED<(N>=0), SIGN<(N>=0)>::value * N>::value;
- };
- #include <iostream>
- int main()
- {
- std::cout<<POW2<0>::value <<"n";
- std::cout<<POW2<1>::value <<"n";
- std::cout<<POW2<4>::value <<"n";
- std::cout<<POW2<7>::value <<"n";
- std::cout<<POW2<-4>::value <<"n";
- }
- 1
- 2
- 16
- 128
- 0.0625
Add Comment
Please, Sign In to add comment