RoundToNearest.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef FBASICS_CASTS_H
  2. #define FBASICS_CASTS_H
  3. #include <cmath>
  4. namespace NICE {
  5. /// round_to_nearest_cast: cast to the nearest value in the target domain
  6. template<typename Target, typename Source> Target round_to_nearest_cast(Source x);
  7. // Allg. round - functor
  8. template<typename Target, typename Source>
  9. struct roundToNearest
  10. {
  11. static Target cast(Source x) { return static_cast<Target>(x); }
  12. };
  13. // Part. spezialisiert
  14. template<typename Source>
  15. struct roundToNearest<long long, Source>
  16. {
  17. static long long cast(Source x) { return static_cast<long long>(floor(x+0.5)); }
  18. };
  19. template<typename Source>
  20. struct roundToNearest<unsigned long long, Source>
  21. {
  22. static unsigned long long cast(Source x) { return static_cast<unsigned long long>(x+0.5); }
  23. };
  24. template<typename Source>
  25. struct roundToNearest<long, Source>
  26. {
  27. static long cast(Source x) { return static_cast<long>(floor(x+0.5)); }
  28. };
  29. template<typename Source>
  30. struct roundToNearest<unsigned long, Source>
  31. {
  32. static unsigned long cast(Source x) { return static_cast<unsigned long>(x+0.5); }
  33. };
  34. template<typename Source>
  35. struct roundToNearest<int, Source>
  36. {
  37. static int cast(Source x) { return static_cast<int>(floor(x+0.5)); }
  38. };
  39. template<typename Source>
  40. struct roundToNearest<unsigned int, Source>
  41. {
  42. static unsigned int cast(Source x) { return static_cast<unsigned int>(x+0.5); }
  43. };
  44. template<typename Source>
  45. struct roundToNearest<char, Source>
  46. {
  47. static char cast(Source x) { return static_cast<char>(floor(x+0.5)); }
  48. };
  49. template<typename Source>
  50. struct roundToNearest<unsigned char, Source>
  51. {
  52. static unsigned char cast(Source x) { return static_cast<unsigned char>(x+0.5); }
  53. };
  54. template<typename Target, typename Source> Target round_to_nearest_cast(Source x)
  55. {
  56. return roundToNearest<Target,Source>::cast(x);
  57. }
  58. } // namespace NICE
  59. #endif // FBASICS_CASTS_H