1 // Copyright 2018 Hans Dembinski
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)
7 #ifndef BOOST_HISTOGRAM_ALGORITHM_SUM_HPP
8 #define BOOST_HISTOGRAM_ALGORITHM_SUM_HPP
10 #include <boost/histogram/accumulators/sum.hpp>
11 #include <boost/histogram/fwd.hpp>
12 #include <boost/mp11/utility.hpp>
14 #include <type_traits>
19 /** Compute the sum over all histogram cells, including underflow/overflow bins.
21 If the value type of the histogram is an integral or floating point type,
22 boost::accumulators::sum<double> is used to compute the sum, else the original value
23 type is used. Compilation fails, if the value type does not support operator+=.
25 Return type is double if the value type of the histogram is integral or floating point,
26 and the original value type otherwise.
28 template <class A, class S>
29 auto sum(const histogram<A, S>& h) {
30 using T = typename histogram<A, S>::value_type;
31 using Sum = mp11::mp_if<std::is_arithmetic<T>, accumulators::sum<double>, T>;
33 for (auto&& x : h) sum += x;
34 using R = mp11::mp_if<std::is_arithmetic<T>, double, T>;
35 return static_cast<R>(sum);
37 } // namespace algorithm
38 } // namespace histogram