9
3

zero.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*!
  2. @file
  3. Defines `boost::hana::zero`.
  4. @copyright Louis Dionne 2013-2017
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_HANA_ZERO_HPP
  9. #define BOOST_HANA_ZERO_HPP
  10. #include <boost/hana/fwd/zero.hpp>
  11. #include <boost/hana/concept/constant.hpp>
  12. #include <boost/hana/concept/monoid.hpp>
  13. #include <boost/hana/config.hpp>
  14. #include <boost/hana/core/to.hpp>
  15. #include <boost/hana/core/dispatch.hpp>
  16. #include <boost/hana/detail/canonical_constant.hpp>
  17. #include <type_traits>
  18. BOOST_HANA_NAMESPACE_BEGIN
  19. //! @cond
  20. template <typename M>
  21. constexpr decltype(auto) zero_t<M>::operator()() const {
  22. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  23. static_assert(hana::Monoid<M>::value,
  24. "hana::zero<M>() requires 'M' to be a Monoid");
  25. #endif
  26. using Zero = BOOST_HANA_DISPATCH_IF(zero_impl<M>,
  27. hana::Monoid<M>::value
  28. );
  29. return Zero::apply();
  30. }
  31. //! @endcond
  32. template <typename M, bool condition>
  33. struct zero_impl<M, when<condition>> : default_ {
  34. template <typename ...Args>
  35. static constexpr auto apply(Args&& ...) = delete;
  36. };
  37. //////////////////////////////////////////////////////////////////////////
  38. // Model for non-boolean arithmetic data types
  39. //////////////////////////////////////////////////////////////////////////
  40. template <typename T>
  41. struct zero_impl<T, when<
  42. std::is_arithmetic<T>::value &&
  43. !std::is_same<T, bool>::value
  44. >> {
  45. static constexpr T apply()
  46. { return static_cast<T>(0); }
  47. };
  48. //////////////////////////////////////////////////////////////////////////
  49. // Model for Constants over a Monoid
  50. //////////////////////////////////////////////////////////////////////////
  51. namespace detail {
  52. template <typename C>
  53. struct constant_from_zero {
  54. static constexpr auto value = hana::zero<typename C::value_type>();
  55. using hana_tag = detail::CanonicalConstant<typename C::value_type>;
  56. };
  57. }
  58. template <typename C>
  59. struct zero_impl<C, when<
  60. hana::Constant<C>::value &&
  61. Monoid<typename C::value_type>::value
  62. >> {
  63. static constexpr decltype(auto) apply()
  64. { return hana::to<C>(detail::constant_from_zero<C>{}); }
  65. };
  66. BOOST_HANA_NAMESPACE_END
  67. #endif // !BOOST_HANA_ZERO_HPP