one.hpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*!
  2. @file
  3. Defines `boost::hana::one`.
  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_ONE_HPP
  9. #define BOOST_HANA_ONE_HPP
  10. #include <boost/hana/fwd/one.hpp>
  11. #include <boost/hana/concept/constant.hpp>
  12. #include <boost/hana/concept/ring.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 R>
  21. constexpr decltype(auto) one_t<R>::operator()() const {
  22. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  23. static_assert(hana::Ring<R>::value,
  24. "hana::one<R>() requires 'R' to be a Ring");
  25. #endif
  26. using One = BOOST_HANA_DISPATCH_IF(one_impl<R>,
  27. hana::Ring<R>::value
  28. );
  29. return One::apply();
  30. }
  31. //! @endcond
  32. template <typename R, bool condition>
  33. struct one_impl<R, 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 one_impl<T, when<std::is_arithmetic<T>::value &&
  42. !std::is_same<bool, T>::value>> {
  43. static constexpr T apply()
  44. { return static_cast<T>(1); }
  45. };
  46. //////////////////////////////////////////////////////////////////////////
  47. // Model for Constants over a Ring
  48. //////////////////////////////////////////////////////////////////////////
  49. namespace detail {
  50. template <typename C>
  51. struct constant_from_one {
  52. static constexpr auto value = hana::one<typename C::value_type>();
  53. using hana_tag = detail::CanonicalConstant<typename C::value_type>;
  54. };
  55. }
  56. template <typename C>
  57. struct one_impl<C, when<
  58. hana::Constant<C>::value &&
  59. Ring<typename C::value_type>::value
  60. >> {
  61. static constexpr decltype(auto) apply()
  62. { return hana::to<C>(detail::constant_from_one<C>{}); }
  63. };
  64. BOOST_HANA_NAMESPACE_END
  65. #endif // !BOOST_HANA_ONE_HPP