always.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*!
  2. @file
  3. Defines `boost::hana::always`.
  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_FUNCTIONAL_ALWAYS_HPP
  9. #define BOOST_HANA_FUNCTIONAL_ALWAYS_HPP
  10. #include <boost/hana/config.hpp>
  11. #include <boost/hana/detail/create.hpp>
  12. #include <utility>
  13. BOOST_HANA_NAMESPACE_BEGIN
  14. //! @ingroup group-functional
  15. //! Return a constant function returning `x` regardless of the
  16. //! argument(s) it is invoked with.
  17. //!
  18. //! Specifically, `always(x)` is a function such that
  19. //! @code
  20. //! always(x)(y...) == x
  21. //! @endcode
  22. //! for any `y...`. A copy of `x` is made and it is owned by the
  23. //! `always(x)` function. When `always(x)` is called, it will return
  24. //! a reference to the `x` it owns. This reference is valid as long
  25. //! as `always(x)` is in scope.
  26. //!
  27. //!
  28. //! ### Example
  29. //! @include example/functional/always.cpp
  30. #ifdef BOOST_HANA_DOXYGEN_INVOKED
  31. constexpr auto always = [](auto&& x) {
  32. return [perfect-capture](auto const& ...y) -> decltype(auto) {
  33. return forwarded(x);
  34. };
  35. };
  36. #else
  37. template <typename T>
  38. struct _always {
  39. T val_;
  40. template <typename ...Args>
  41. constexpr T const& operator()(Args const& ...) const&
  42. { return val_; }
  43. template <typename ...Args>
  44. constexpr T& operator()(Args const& ...) &
  45. { return val_; }
  46. template <typename ...Args>
  47. constexpr T operator()(Args const& ...) &&
  48. { return std::move(val_); }
  49. };
  50. constexpr detail::create<_always> always{};
  51. #endif
  52. BOOST_HANA_NAMESPACE_END
  53. #endif // !BOOST_HANA_FUNCTIONAL_ALWAYS_HPP