Imported Upstream version 1.64.0
[platform/upstream/boost.git] / boost / hana / sum.hpp
1 /*!
2 @file
3 Defines `boost::hana::sum`.
4
5 @copyright Louis Dionne 2013-2017
6 Distributed under the Boost Software License, Version 1.0.
7 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
8  */
9
10 #ifndef BOOST_HANA_SUM_HPP
11 #define BOOST_HANA_SUM_HPP
12
13 #include <boost/hana/fwd/sum.hpp>
14
15 #include <boost/hana/concept/foldable.hpp>
16 #include <boost/hana/concept/monoid.hpp>
17 #include <boost/hana/config.hpp>
18 #include <boost/hana/core/dispatch.hpp>
19 #include <boost/hana/fold_left.hpp>
20 #include <boost/hana/integral_constant.hpp> // required by fwd decl
21 #include <boost/hana/plus.hpp>
22 #include <boost/hana/zero.hpp>
23
24
25 BOOST_HANA_NAMESPACE_BEGIN
26     template <typename M>
27     struct sum_t {
28     #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
29         static_assert(hana::Monoid<M>::value,
30         "hana::sum<M> requires 'M' to be a Monoid");
31     #endif
32
33         template <typename Xs>
34         constexpr decltype(auto) operator()(Xs&& xs) const {
35             using S = typename hana::tag_of<Xs>::type;
36             using Sum = BOOST_HANA_DISPATCH_IF(sum_impl<S>,
37                 hana::Foldable<S>::value
38             );
39
40         #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
41             static_assert(hana::Foldable<S>::value,
42             "hana::sum<M>(xs) requires 'xs' to be Foldable");
43         #endif
44
45             return Sum::template apply<M>(static_cast<Xs&&>(xs));
46         }
47     };
48
49     template <typename T, bool condition>
50     struct sum_impl<T, when<condition>> : default_ {
51         template <typename M, typename Xs>
52         static constexpr decltype(auto) apply(Xs&& xs) {
53             return hana::fold_left(static_cast<Xs&&>(xs), hana::zero<M>(), hana::plus);
54         }
55     };
56 BOOST_HANA_NAMESPACE_END
57
58 #endif // !BOOST_HANA_SUM_HPP