Guest User

Untitled

a guest
May 24th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. // Sign of an integer
  2. template<bool b> struct SIGN {static const int value = ( b * 2 ) - 1; };
  3.  
  4. // Positive powers of two (fast exponentiation)
  5. template<unsigned int N> struct POW2_POS {
  6. static const float value =
  7. POW2_POS<N%2>::value
  8. * POW2_POS<N/2>::value
  9. * POW2_POS<N/2>::value;
  10. };
  11. template<> struct POW2_POS <1> { static const float value = 2.0f; };
  12. template<> struct POW2_POS <0> { static const float value = 1.0f; };
  13.  
  14. // Negative powers of two
  15. template<unsigned int N> struct POW2_NEG {static const float value = 1.0f / POW2_POS<N>::value; };
  16.  
  17. // Calls POW2_POS or POW2_NEG depending on boolean parameter
  18. template<bool b, int N> struct POW2_SIGNED;
  19. template<int N> struct POW2_SIGNED<true, N> { static const float value = POW2_POS<N>::value;};
  20. template<int N> struct POW2_SIGNED<false, N> { static const float value = POW2_NEG<N>::value;};
  21.  
  22. // Integer power of two
  23. template<int N> struct POW2 {
  24. static const float value = POW2_SIGNED<(N>=0), SIGN<(N>=0)>::value * N>::value;
  25. };
  26.  
  27. #include <iostream>
  28. int main()
  29. {
  30. std::cout<<POW2<0>::value <<"n";
  31. std::cout<<POW2<1>::value <<"n";
  32. std::cout<<POW2<4>::value <<"n";
  33. std::cout<<POW2<7>::value <<"n";
  34. std::cout<<POW2<-4>::value <<"n";
  35. }
  36.  
  37. 1
  38. 2
  39. 16
  40. 128
  41. 0.0625
Add Comment
Please, Sign In to add comment