sum.hpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2018 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_HISTOGRAM_ALGORITHM_SUM_HPP
  7. #define BOOST_HISTOGRAM_ALGORITHM_SUM_HPP
  8. #include <boost/histogram/accumulators/sum.hpp>
  9. #include <boost/histogram/fwd.hpp>
  10. #include <boost/mp11/utility.hpp>
  11. #include <numeric>
  12. #include <type_traits>
  13. namespace boost {
  14. namespace histogram {
  15. namespace algorithm {
  16. /** Compute the sum over all histogram cells, including underflow/overflow bins.
  17. If the value type of the histogram is an integral or floating point type,
  18. boost::accumulators::sum<double> is used to compute the sum, else the original value
  19. type is used. Compilation fails, if the value type does not support operator+=.
  20. Return type is double if the value type of the histogram is integral or floating point,
  21. and the original value type otherwise.
  22. */
  23. template <class A, class S>
  24. auto sum(const histogram<A, S>& h) {
  25. using T = typename histogram<A, S>::value_type;
  26. using Sum = mp11::mp_if<std::is_arithmetic<T>, accumulators::sum<double>, T>;
  27. Sum sum;
  28. for (auto&& x : h) sum += x;
  29. using R = mp11::mp_if<std::is_arithmetic<T>, double, T>;
  30. return static_cast<R>(sum);
  31. }
  32. } // namespace algorithm
  33. } // namespace histogram
  34. } // namespace boost
  35. #endif